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

6 ビュー (過去 30 日間)
Kim
Kim 2015 年 10 月 24 日
コメント済み: Star Strider 2015 年 10 月 24 日
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.
  2 件のコメント
Kim
Kim 2015 年 10 月 24 日
Star Thank you very much!
Star Strider
Star Strider 2015 年 10 月 24 日
My pleasure!
I had fun programming it!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by