java编写一个代表三角形的类,其中3条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别利用3条边为3、4、5和7、8、9的两个三角形进行测试。
时间: 2024-02-15 17:04:27 浏览: 92
好的,以下是Java代码实现:
```java
public class Triangle {
private double sideA;
private double sideB;
private double sideC;
public Triangle(double sideA, double sideB, double sideC) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
public double getSideA() {
return sideA;
}
public void setSideA(double sideA) {
this.sideA = sideA;
}
public double getSideB() {
return sideB;
}
public void setSideB(double sideB) {
this.sideB = sideB;
}
public double getSideC() {
return sideC;
}
public void setSideC(double sideC) {
this.sideC = sideC;
}
public double getArea() {
double p = (sideA + sideB + sideC) / 2;
return Math.sqrt(p * (p - sideA) * (p - sideB) * (p - sideC));
}
public double getPerimeter() {
return sideA + sideB + sideC;
}
}
```
接下来进行测试:
```java
public class Main {
public static void main(String[] args) {
Triangle t1 = new Triangle(3, 4, 5);
System.out.println("t1: ");
System.out.println("Area: " + t1.getArea());
System.out.println("Perimeter: " + t1.getPerimeter());
Triangle t2 = new Triangle(7, 8, 9);
System.out.println("t2: ");
System.out.println("Area: " + t2.getArea());
System.out.println("Perimeter: " + t2.getPerimeter());
}
}
```
输出结果为:
```
t1:
Area: 6.0
Perimeter: 12.0
t2:
Area: 26.832815729997478
Perimeter: 24.0
```
可以看到,输出结果符合预期,算法正确。
阅读全文