用java编写一个三角形类,能根据三个实数构造三角形对象,如果三个实数不满足三角形 的条件,则自动构造以最小值为边的等边三角形。输入任意三个数,输出构造的三角形面积。
时间: 2024-05-14 12:14:16 浏览: 81
三角形面积的java代码
```java
public class Triangle {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
// 不满足三角形条件,构造最小值为边长的等边三角形
this.a = this.b = this.c = Math.min(Math.min(a, b), c);
} else {
this.a = a;
this.b = b;
this.c = c;
}
}
public double getArea() {
double p = (a + b + c) / 2; // 半周长
return Math.sqrt(p * (p - a) * (p - b) * (p - c)); // 海伦公式求面积
}
}
```
测试代码:
```java
public class TestTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
Triangle triangle = new Triangle(a, b, c);
System.out.println(triangle.getArea());
}
}
```
阅读全文