Reputation: 43
Write a program that prompts for the lengths of the sides of a triangle and reports the three angles.
I am not getting angles that equal to 180, and for some cases I am getting NaN for some angle values.
My code is shown below
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);
}
Upvotes: 2
Views: 972
Reputation: 270733
The problem lies in these three lines:
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
does not mean "squared". It means "bitwise XOR 2". You need to use a*a
or Math.pow(a, 2)
for "a squared".
So the three lines should be:
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)));
Also, the getSideX
methods could be combined into one and the scanner could be extracted to the class level:
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;
}
Your main
method now looks like this:
public static void main(String[] args) {
int a = getSide("A");
int b = getSide("B");
int c = getSide("C");
giveSides(a, b, c);
}
Upvotes: 4