编写一个程序,提示输入三角形的边长并报告三个角度。
我没有得到等于 180 的角度,在某些情况下,某些角度值获得了 NaN 。
我的代码如下所示
public static int getSideA() {
System.out.println("What is the length of side a?");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
return a;
}
public static int getSideB() {
System.out.println("What is the length of side b?");
Scanner console = new Scanner(System.in);
int b = console.nextInt();
return b;
}
public static int getSideC() {
System.out.println("What is the length of side C");
Scanner console = new Scanner(System.in);
int c = console.nextInt();
return c;
}
public static void giveSides(int a, int b, int c) {
double angleA = Math.toDegrees(Math.acos((a^2 - b^2 - c^2) / (-2.0 * c * b)));
double angleB = Math.toDegrees(Math.acos((b^2 - a^2 - c^2) / (-2.0 * a * c)));
double angleC = Math.toDegrees(Math.acos((c^2 - a^2 - b^2) / (-2.0 * a * b)));
System.out.println("The three angles are: " + angleA + " " + angleB + " " + angleC);
}
public static void main(String[] args) {
int a = getSideA();
int b = getSideB();
int c = getSideC();
giveSides(a, b, c);
}
答案 0 :(得分:4)
问题出在以下三行:
double angleA = Math.toDegrees(Math.acos((a^2 - b^2 - c^2) / (-2.0 * c * b)));
double angleB = Math.toDegrees(Math.acos((b^2 - a^2 - c^2) / (-2.0 * a * c)));
double angleC = Math.toDegrees(Math.acos((c^2 - a^2 - b^2) / (-2.0 * a * b)));
^2
并不表示“平方”。这意味着“按位XOR 2”。您需要将a*a
或Math.pow(a, 2)
用作“平方”。
所以三行应该是:
double angleA = Math.toDegrees(Math.acos((a*a - b*b - c*c) / (-2.0 * c * b)));
double angleB = Math.toDegrees(Math.acos((b*b - a*a - c*c) / (-2.0 * a * c)));
double angleC = Math.toDegrees(Math.acos((c*c - a*a - b*b) / (-2.0 * a * b)));
此外,getSideX
方法可以合并为一个,并且可以将扫描器提取到类级别:
static Scanner console = new Scanner(System.in);
public static int getSide(String name) {
System.out.println("What is the length of side " + name + "?");
int a = console.nextInt();
return a;
}
您的main
方法现在看起来像这样:
public static void main(String[] args) {
int a = getSide("A");
int b = getSide("B");
int c = getSide("C");
giveSides(a, b, c);
}