Trying to find if three inputed numbers can make a right triangle

6 Ansichten (letzte 30 Tage)
Can anyone help? I am trying to see if an array of three numbers inputted by a user can form a right triangle. My code is below and I can't figure out why it won't work. Thank you in advance!
sides =input('please enter 3 whole numbers in brackets [] : ');
Sides = perms(sides);% generate an array of the permutations of the input
Triange=0% initiate count
for a = 1:3
for b = 1:3
for c = 1:3
if (Sides(:,a)^ 2)+ (Sides(:,b)^ 2) == (Sides(:,c) ^ 2);
Tri(:,:) = [Sides(:,a),Sides(:,b),Sides(:,c)];
Triangle=Triangle +1
else disp('there are no right triangles')
end
end% for c
end% for b
end%for a

Akzeptierte Antwort

Star Strider
Star Strider am 24 Okt. 2015
It is difficult for me to follow your code. I would do it this way:
sortsides = sort(sides);
istri = sum(sortsides(1:2)) >= sortsides(3); % Will The 3 Numbers Form A Triangle?
isrightri = sum(sortsides(1:2).^2) == sortsides(3).^2; % Is It A Right Triangle?
if isrightri
fprintf('\n\tThe numbers {%d, %d, %d} form a right triangle.\n', sortsides)
elseif istri && ~isrightri
fprintf('\n\tThe numbers {%d, %d, %d} do not form a right triangle.\n', sortsides)
elseif ~istri
fprintf('\n\tThe numbers {%d, %d, %d} do not form any triangle.\n', sortsides)
end
The ‘sortsides’ assignment sorts the sides in ascending order. This is important for the efficiency of the code! If the sum of the lengths of the two shorter sides is greater that the length of the third side, then you can form a triangle (the istri assignment), otherwise it is impossible to form any triangle from them. Then determine if it is a right triangle, using the Pythagorean Theorem.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by