Java 从三个侧面计算的角度仅显示90度或180度
这就是问题所在:编写一个程序,提示输入三角形边的长度,并报告三个角度 我为此编写了以下代码:Java 从三个侧面计算的角度仅显示90度或180度,java,Java,这就是问题所在:编写一个程序,提示输入三角形边的长度,并报告三个角度 我为此编写了以下代码: public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Please input length of side A: "); int sideA = console.nextInt();
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please input length of side A: ");
int sideA = console.nextInt();
System.out.print("Please input length of side B: ");
int sideB = console.nextInt();
System.out.print("Please input length of side C: ");
int sideC = console.nextInt();
System.out.println();
System.out.println("The angle between A and B is: " + calculateAngle(sideA, sideB, sideC));
System.out.println("The angle between B and C is: " + calculateAngle(sideB, sideC, sideA));
System.out.println("The angle between C and A is: " + calculateAngle(sideC, sideA, sideB));
}
public static double calculateAngle(int a, int b, int c) {
return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));
}
下面是我上面代码的示例输出:
Please input length of side A: 55
Please input length of side B: 22
Please input length of side C: 76
The angle between A and B is: 90.0
The angle between B and C is: 90.0
The angle between C and A is: 90.0
无论我为边输入什么值,我得到的唯一角度都是90度或180度,而不是可以根据余弦规则计算的实际正确角度。我的代码有什么问题?只需将
Math.acos
中的计算转换为double
:
return Math.toDegrees(Math.acos((double)(a * a + b * b - c * c) / (2 * a * b)));
正如您在注释中所看到的,当在多个int
类型之间进行计算时,将使用integer
算法,然后将其转换为double
另外值得注意的是,int
总是向下取整,意思是:
int i = 0.9999999; // i = 0
根据文件,他们希望
acos
方法的参数为双值
所以像这样重新安排代码
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please input length of side A: ");
double sideA = console.nextDouble();
System.out.print("Please input length of side B: ");
double sideB = console.nextDouble();
System.out.print("Please input length of side C: ");
double sideC = console.nextDouble();
System.out.println();
System.out.println("The angle between A and B is: " + calculateAngle(sideA, sideB, sideC));
System.out.println("The angle between B and C is: " + calculateAngle(sideB, sideC, sideA));
System.out.println("The angle between C and A is: " + calculateAngle(sideC, sideA, sideB));
}
public static double calculateAngle(double a, double b, double c) {
return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));
}
为了澄清@Aplet123注释-整数除法意味着计算中的
acos
始终为零,即90度。将变量更改为float
或double
,或在计算中强制转换结果。谢谢!成功了!不客气。