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

1 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2015-10-24
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by