第八章第三十二题(几何:三角形面积)(triangle area)
-
*8.32(几何:三角形面积)编写一个方法,使用下面的方法头,返回一个三角形的面积:
public static double getTriangleArea(double[][] points)
这些点保存在一个4x2的二维数组points中,其中(points[0][0],points[0][1])代表(x1,y1)。三角形面积的计算可以使用编程练习题2.19中的公式。如果三个点在一条直线上,方法返回0.编写一个程序,提示用户输入三角形的三个点,然后显示三角形的面积。下面是一个运行示例。
Enter x1,y1,x2,y2,x3,y3 : 2.5 2 5 -1.0 4.0 2.0
The area of the triangle is 2.2500000000000013
Enter x1,y1,x2,y2,x3,y3 : 2 2 4.5 4.5 6 6
The three points are on the same line
*8.32(triangle area)Write a method, use the following method header to return the area of a triangle:
public static double getTriangleArea(double[][] points)
These points are stored in the two-dimensional array [1 s] [0] in [1 s] [0]. The calculation of triangle area can use the formula in programming exercise 2.19. If three points are on a straight line, the method returns 0. Write a program to prompt the user to input three points of the triangle, and then display the area of the triangle. Here is a running example.
Enter x1,y1,x2,y2,x3,y3 : 2.5 2 5 -1.0 4.0 2.0
The area of the triangle is 2.2500000000000013
Enter x1,y1,x2,y2,x3,y3 : 2 2 4.5 4.5 6 6
The three points are on the same line -
参考代码:
package chapter08; import java.util.Scanner; public class Code_32 { public static void main(String[] args) { double[][] points = new double[3][2]; System.out.print("Enter x1,y1,x2,y2,x3,y3 : "); Scanner PointsInput = new Scanner(System.in); points[0][0] = PointsInput.nextDouble(); points[0][1] = PointsInput.nextDouble(); points[1][0] = PointsInput.nextDouble(); points[1][1] = PointsInput.nextDouble(); points[2][0] = PointsInput.nextDouble(); points[2][1] = PointsInput.nextDouble(); if (!isParrallel(points)) System.out.println("The area of the triangle is " + getTriangleArea(points)); else System.out.println("The three points are on the same line"); PointsInput.close(); } public static double getTriangleArea(double[][] points){ double LengthSide1 = getSide(points[0][0],points[0][1],points[1][0],points[1][1]); double LengthSide2 = getSide(points[2][0],points[2][1],points[1][0],points[1][1]); double LengthSide3 = getSide(points[0][0],points[0][1],points[2][0],points[2][1]); double HalfSumLengthSide = (LengthSide1 + LengthSide2 + LengthSide3) / 2; return Math.pow(HalfSumLengthSide * (HalfSumLengthSide - LengthSide1) * (HalfSumLengthSide - LengthSide2) * (HalfSumLengthSide - LengthSide3), 0.5); } public static double getSide(double x1,double y1,double x2,double y2){ return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } public static boolean isParrallel(double[][] points){ double k1 = (points[1][1] - points[0][1]) / (points[1][0] - points[0][0]); double k2 = (points[2][1] - points[2][1]) / (points[1][0] - points[0][0]); if (k1 == k2) return false; return true; } }
-
结果显示:
Enter x1,y1,x2,y2,x3,y3 : 2 2 4.5 4.5 6 6 The three points are on the same line Process finished with exit code 0