编写一个代表三角形的类,其中3条边为三角形的属性,并封装有求三角形的面积和周长的方法。分别利用3条边为3、4、5和7、8、9的两个三角形进行测试。
时间: 2023-05-28 10:03:49 浏览: 91
```python
class Triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimeter(self):
return self.a + self.b + self.c
def area(self):
s = (self.a + self.b + self.c) / 2
return (s * (s-self.a) * (s-self.b) * (s-self.c)) ** 0.5
triangle1 = Triangle(3, 4, 5)
print("Triangle 1 perimeter:", triangle1.perimeter())
print("Triangle 1 area:", triangle1.area())
triangle2 = Triangle(7, 8, 9)
print("Triangle 2 perimeter:", triangle2.perimeter())
print("Triangle 2 area:", triangle2.area())
```
输出结果:
```
Triangle 1 perimeter: 12
Triangle 1 area: 6.0
Triangle 2 perimeter: 24
Triangle 2 area: 26.832815729997478
```
阅读全文