题目要求:
编写程序,提示用户输入三角形的三个点(x1, y1),(x2, y2), (x3, y3),然后显示它的面积。计算三角形面积的公式是: s=(s1+s2+s3)/2;面积 = )3)(2)(1(sssssss其中s1,s2, s3分别为三角形三边的长度。
输入示例:
Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.6
源程序:
import java.text.DecimalFormat ;
import java.util.Scanner;
/**
* @Author 黄佳浩
* @Time 2020-04-17
* @Theme 控制结构
*/
public class Experiment_02 {
public static void main(String[] args) {
//创建扫描器
Scanner sc = new Scanner(System.in) ;
//提示用户输入三个点的坐标值
System.out.print("Enter three points for a triangle: ");
double x1 = sc.nextDouble() ;
double y1 = sc.nextDouble() ;
double x2 = sc.nextDouble() ;
double y2 = sc.nextDouble() ;
double x3 = sc.nextDouble() ;
double y3 = sc.nextDouble() ;
//创建三角形对象
Triangle triangle = new Triangle(x1,y1,x2,y2,x3,y3);
//获取面积并保留两位小数
DecimalFormat df = new DecimalFormat("0.00") ;
if (triangle.getArea()!= 0){
System.out.println("The area of the triangle is "+df.format(triangle.getArea()));
}else{
System.out.println("无法构成三角形请检查后重试!!");
}
}
}
class Triangle{
public double x1 ;
public double y1 ;
public double x2 ;
public double y2 ;
public double x3 ;
public double y3 ;
public Triangle(double x1 ,double y1 ,double x2,double y2,double x3,double y3){
this.x1 = x1 ;
this.y1 = y1 ;
this.x2 = x2 ;
this.y2 = y2 ;
this.x3 = x3 ;
this.y3 = y3 ;
}
public double getArea(){
//第一条边长度s1
double s1 = Math.sqrt(Math.pow(x2-x1 ,2 )+Math.pow(y2-y1 , 2)) ;
//第二条边长度s2
double s2 = Math.sqrt(Math.pow(x3-x1 ,2 )+Math.pow(y3-y1 , 2)) ;
//第三条边长度s3
double s3 = Math.sqrt(Math.pow(x3-x2 ,2 )+Math.pow(y3-y2 , 2)) ;
//周长的一半
double s = 0.5*(s1+s2+s3) ;
if (s1+s2>s3&&s1+s3>s2&&s2+s3>s1){
return Math.sqrt(s*(s-s1)*(s-s2)*(s-s3)) ;
}else{
//返回0代表无法构成三角形
return 0 ;
}
}
}
运行结果: