[英]Write a program that prompts for the lengths of the sides of a triangle and reports the three angles
[英]Program to determine if 3 sides form a valid triangle using Java
给定三个整数 a、b 和 c,如果 a、b 和 c 可能是直角三角形的边长,则返回 true。 否则返回假。 回想一下,在直角三角形中,每条边的长度都必须为正,并且腿长的平方和必须等于斜边长度的平方。
isRightTriangle(3, 4, 5) → true isRightTriangle(4, 3, 5) → true isRightTriangle(5, 4, 3) → true
boolean isRightTriangle(int a, int b, int c) {
if(a>0 && b>0 && c>0){
if((Math.sqrt((double)a)+Math.sqrt((double)b))==Math.sqrt((double)c)){
return true;
}
else{
if((Math.sqrt((double)b)+Math.sqrt((double)c))==Math.sqrt((double)a)){
return true;
}
else{
if((Math.sqrt(c)+Math.sqrt(b))==Math.sqrt(a)){
return true;
}
else{
return false;
}
}
}
}
else{
return false;
}
}
您正在使用 Math.sqrt 而不是 Math.pow(x, 2)。 您需要检查 a^2+b^2=c^2,而不是 sqrt(a)+sqrt(b)=sqrt(c)。
boolean isRightTriangle(int a, int b, int c) {
// lets exit if variables are bad
if(a < 1 || b < 1 || c < 1) {
return false;
}
// lets create an array so we can sort
int[] arry = new int[3];
arry[0] = a;
arry[1] = b;
arry[2] = c;
Arrays.sort(arry);
// now that the array is sorted, the largest number (the hypotenuse) should be arry[2]
return Math.pow(arry[0], 2) + Math.pow(arry[1], 2) == Math.pow(arry[2], 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.