java程序设计1-2之用海伦公式计算三角形的面积
(第62页2.19)计算三角形的面积。输入三角形的三个点(x1,y1),(x2,y2)和(x3,y3),计算三解形的面积。
源程序如下:
package demo;
import java.util.Scanner;
publicclass MySquareOfTriangle {
double x1, x2, x3, y1, y2, y3;
Scanner =new Scanner(System.in );
System.out .print("Enter three points for a triangle:");
x1=input .nextDouble();
y1=input .nextDouble();
x2=input .nextDouble();
y2=input .nextDouble();
x3=input .nextDouble();
y3=input .nextDouble();
double a1=x2-x1;
double a2=y2-y1;
double b1=x3-x1;
double b2=y3-y1;
double c1=x3-x2;
double c2=y3-y2;
double i1=Math.pow (a1, 2);
double i2=Math.pow (a2, 2);
double i3=i1+i2;
double sideOne =Math.pow (i3, 0.5);
double j1=Math.pow (b1, 2);
double j2=Math.pow (b2, 2);
double j3=j1+j2;
double sideTwo =Math.pow (j3, 0.5);
double k1=Math.pow (c1, 2);
double k2=Math.pow (c2, 2);
double k3=k1+k2; publicstaticvoid main(String[] args ) { // TODO Auto-generated method stub
double sideThree =Math.pow (k3, 0.5);
double s =(sideOne +sideTwo +sideThree )/2;
double h =s *(s -sideOne )*(s -sideTwo )*(s -sideThree );
double square =Math.pow (h , 0.5);
System.out .println("The area of triangle is:"+(int )(square *10)/10.0);//保留一位小数
} }
结果实例1:
Enter three points for a triangle:1.5 -3.4 4.6 5 9.5 -3.4
The area of triangle is:33.6
如图所示:
结果实例2:
Enter three points for a triangle:0 0 3 0 0 4 The area of triangle is:6.0
如图所示: