gpt4 book ai didi

java - 编写一个程序,提示输入三角形的边长并报告三个角度

转载 作者:行者123 更新时间:2023-11-30 06:41:23 25 4
gpt4 key购买 nike

编写一个程序,提示输入三角形的边长并报告三个角度。

我没有得到等于 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);
}

最佳答案

问题出在这三行:

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 并不表示“平方”。它的意思是“按位异或 2”。您需要使用 a*aMath.pow(a, 2) 来表示“a 平方”。

所以这三行应该是:

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);
}

关于java - 编写一个程序,提示输入三角形的边长并报告三个角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com