所以我有这段代码提示输入两侧的空格分隔输入和三角形的斜边。如果三角形是正确的,则 main 下面的方法应该返回 true,否则返回 false。
出于某种原因,即使我知道我输入的测量值是针对直角三角形的,它仍然会打印出三角形不是直角三角形。
一段时间以来,我一直在尝试检测此代码中的逻辑错误,可以帮忙/叫我出来吗?
import java.util.Scanner;
public class VerifyRightTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the two sides and the hypotenuse: ");
String input = sc.nextLine();
String[] values = input.split(" ");
int[] nums = new int[values.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.parseInt(values[i]);
}
double s1 = nums[0];
double s2 = nums[1];
double hyp = nums[2];
System.out.printf("Side 1: %.2f Side 2: %.2f Hypotenuse: %.2f\n", s1, s2, hyp);
boolean result = isRightTriangle(s1, s2, hyp);
if (result == true) {
System.out.println("The given triangle is a right triangle.");
} else if (result == false) {
System.out.println("The given triangle is not a right triangle.");
}
}
/**
* Determine if the triangle is a right triangle or not, given the shorter side, the longer
* side, and the hypotenuse (in that order), using the Pythagorean theorem.
* @param s1 the shorter side of the triangle
* @param s2 the longer side of the triangle
* @param hyp the hypotenuse of the triangle
* @return true if triangle is right, false if not
*/
private static boolean isRightTriangle(double s1, double s2, double hyp) {
double leftSide = s1 * s1 + s2 * s2;
double rightSide = hyp * hyp;
if (Math.sqrt(leftSide) == Math.sqrt(rightSide)) {
return true;
} else {
return false;
}
}
}