第二章第十九题(几何:三角形的面积)(Geometry: area of a triangle)
-
*2.19(几何:三角形的面积)编写程序,提示用户输入三角形的三个点(x1,y1)、(x2,y2)和(x3,y3),然后显示它的面积。计算三角形面积的公式是:
下面是一个运行示例:
Enter the coordinates of three points separated by spaces\nlike x1 y1 x2 y2 x3 y3 : 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.6
*2.19(Geometry: area of a triangle) Write a program that prompts the user to enter three
points, (x1, y1), (x2, y2), and (x3, y3), of a triangle then displays its area.
The formula for computing the area of a triangle is
Here is a simple run:
Enter the coordinates of three points separated by spaces\nlike x1 y1 x2 y2 x3 y3 : 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.6
-
参考代码:
package chapter02;
import java.util.Scanner;
public class Code_19 {
public static void main(String[] args) {
double x1, y1;
double x2, y2;
double x3, y3;
//distance between two points
double LengthSide1, LengthSide2, LengthSide3;
//HalfSumLengthSide represent that half of summation of all of sides
double HalfSumLengthSide, AreaTriangle;
System.out.print("Enter the coordinates of three points separated"
+ " by spaces\nlike x1 y1 x2 y2 x3 y3 : ");
Scanner PointsInput = new Scanner(System.in);
x1 = PointsInput.nextDouble(); y1 = PointsInput.nextDouble();
x2 = PointsInput.nextDouble(); y2 = PointsInput.nextDouble();
x3 = PointsInput.nextDouble(); y3 = PointsInput.nextDouble();
LengthSide1 = Math.pow(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2), 0.5);
LengthSide2 = Math.pow(Math.pow(x3-x1, 2) + Math.pow(y3-y1, 2), 0.5);
LengthSide3 = Math.pow(Math.pow(x3-x2, 2) + Math.pow(y3-y2, 2), 0.5);
HalfSumLengthSide = (LengthSide1 + LengthSide2 + LengthSide3) / 2;
AreaTriangle = Math.pow(HalfSumLengthSide
*(HalfSumLengthSide - LengthSide1)
*(HalfSumLengthSide - LengthSide2)
*(HalfSumLengthSide - LengthSide3), 0.5);
System.out.println("The area of the triangle is " + AreaTriangle);
PointsInput.close();
}
}
- 结果显示:
Enter the coordinates of three points separated by spaces
like x1 y1 x2 y2 x3 y3 : 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.600000000000016
Process finished with exit code 0