Java Reference
In-Depth Information
4.2.6 Case Study: Computing Angles of a Triangle
You can use the math methods to solve many computational problems. Given the three sides
of a triangle, for example, you can compute the angles by using the following formula:
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
x2, y2
a
B
c
C
x3, y3
A
b
x1, y1
Don't be intimidated by the mathematic formula. As we discussed early in ListingĀ 2.9,
ComuteLoan.java, you don't have to know how the mathematical formula is derived in order
to write a program for computing the loan payments. Here in this example, given the length of
three sides, you can use this formula to write a program to compute the angles without having
to know how the formula is derived. In order to compute the lengths of the sides, we need to
know the coordinates of three corner points and compute the distances between the points.
ListingĀ 4.1 is an example of a program that prompts the user to enter the x- and y-coordinates
of the three corner points in a triangle and then displays the three angles.
L
ISTING
4.1
ComputeAngles.java
1
import
java.util.Scanner;
2
3
public class
ComputeAngles {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6
7
// Prompt the user to enter three points
8 System.out.print(
"Enter three points: "
);
9
double
x1 = input.nextDouble();
enter three points
10
double
y1 = input.nextDouble();
11
double
x2 = input.nextDouble();
12
double
y2 = input.nextDouble();
13
double
x3 = input.nextDouble();
14
double
y3 = input.nextDouble();
15
16
// Compute three sides
17
double
a = Math.sqrt((x2 - x3) * (x2 - x3)
18 + (y2 - y3) * (y2 - y3));
19
double
b = Math.sqrt((x1 - x3) * (x1 - x3)
20 + (y1 - y3) * (y1 - y3));
21
double
c = Math.sqrt((x1 - x2) * (x1 - x2)
22 + (y1 - y2) * (y1 - y2));
23
24
// Compute three angles
25
double
A = Math.toDegrees(Math.acos((a * a - b * b - c * c)
26 / (
-2
* b * c)));
27
double
B = Math.toDegrees(Math.acos((b * b - a * a - c * c)
28 / (
-2
* a * c)));
29
double
C = Math.toDegrees(Math.acos((c * c - b * b - a * a)
30 / (
-2
* a * b)));
31
32
// Display results
33 System.out.println(
"The three angles are "
+
34 Math.round(A *
100
) /
100
.
0
+
" "
+
compute sides
display result
Search WWH ::
Custom Search