第二章第十九题(几何:三角形的面积)(Geometry: area of a triangle)

*2.19(几何:三角形的面积)编写程序,提示用户输入三角形的三个点(x1,y1)、(x2,y2)和(x3,y3),然后显示它的面积。计算三角形面积的公式是:

s = (side1 + side2 + side3) / 2

area = \sqrt{s(s-side1)(s-side2)(s-side3))}

下面是一个运行示例:

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

s = (side1 + side2 + side3) / 2

area = \sqrt{s(s-side1)(s-side2)(s-side3))}

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

 

下面是参考答案代码:

import java.util.*;


public class AreaTriangleQuestion19 {
	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();
	}
}

运行效果:

 

注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)

你可能感兴趣的:(#,第二章课后习题答案)