java—从三个侧面计算的Angular 只能显示90度或180度

utugiqy6  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(237)

这个问题在这里已经有答案了

整数除法:为什么1/3的结果==0((16个答案)
24天前关门。
这就是问题所在:编写一个程序,提示输入三角形边的长度,并报告三个Angular 。
我为此编写了以下代码:

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

无论我为边输入什么值,我得到的唯一Angular 都是90度或180度,而不是可以根据余弦规则计算出的实际正确Angular 。我的代码怎么了?

cunj1qz1

cunj1qz11#

算了算就行了 Math.acosdouble :

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
ux6nzvsh

ux6nzvsh2#

根据文档,他们期望一个双精度值作为他们的参数 acos 方法javase7 math doc
所以像这样重新排列你的代码

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

相关问题