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

时间:2019-04-25 06:30:07

标签: java

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

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

1 个答案:

答案 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*aMath.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);
}