java 求三角形面积
时间: 2023-11-20 13:56:29 浏览: 96
以下是Java求三角形面积的代码示例:
```java
public class Triangle {
private double x1, y1, x2, y2, x3, y3; // 三角形三个点的坐标
private double area; // 三角形的面积
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 void calculateArea() {
double a = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
double b = Math.sqrt(Math.pow(x2 - x3, 2) + Math.pow(y2 - y3, 2));
double c = Math.sqrt(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2));
double s = (a + b + c) / 2;
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// 输出三角形坐标和面积的方法
public void print() {
System.out.println("(" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ") (" + x3 + "," + y3 + ")");
System.out.println("area=" + area);
}
public static void main(String[] args) {
Triangle tri = new Triangle(1, 1, 4, 1, 4, 5);
tri.calculateArea();
tri.print();
}
}
```
阅读全文