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

6 vues (au cours des 30 derniers jours)
Kim
Kim le 24 Oct 2015
Commenté : Star Strider le 24 Oct 2015
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

Réponse acceptée

Star Strider
Star Strider le 24 Oct 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.
  2 commentaires
Kim
Kim le 24 Oct 2015
Star Thank you very much!
Star Strider
Star Strider le 24 Oct 2015
My pleasure!
I had fun programming it!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by