海伦公式求三角形面积java
时间: 2023-11-20 20:56:40 浏览: 177
易语言海伦公式求三角形面积源码
以下是使用海伦公式求三角形面积的Java代码:
```java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Triangle {
private Point a;
private Point b;
private Point c;
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getPerimeter() {
double ab = Math.sqrt(Math.pow(a.getX() - b.getX(), 2) + Math.pow(a.getY() - b.getY(), 2));
double bc = Math.sqrt(Math.pow(b.getX() - c.getX(), 2) + Math.pow(b.getY() - c.getY(), 2));
double ac = Math.sqrt(Math.pow(a.getX() - c.getX(), 2) + Math.pow(a.getY() - c.getY(), 2));
return ab + bc + ac;
}
public double getArea() {
double ab = Math.sqrt(Math.pow(a.getX() - b.getX(), 2) + Math.pow(a.getY() - b.getY(), 2));
double bc = Math.sqrt(Math.pow(b.getX() - c.getX(), 2) + Math.pow(b.getY() - c.getY(), 2));
double ac = Math.sqrt(Math.pow(a.getX() - c.getX(), 2) + Math.pow(a.getY() - c.getY(), 2));
double p = (ab + bc + ac) / 2;
return Math.sqrt(p * (p - ab) * (p - bc) * (p - ac));
}
}
public class Test {
public static void main(String[] args) {
Point a = new Point(0, 0);
Point b = new Point(3, 0);
Point c = new Point(0, 4);
Triangle triangle = new Triangle(a, b, c);
System.out.println("Perimeter: " + triangle.getPerimeter()); // 输出:Perimeter: 12.0
System.out.println("Area: " + triangle.getArea()); // 输出:Area: 6.0
}
}
```
阅读全文