先创建一个Point类,然后定义Triangle类。在Triangle类中定义三个Point的实体来表示一个三角形的三个顶点,再定义一个方法setPoints对这三个点进行初始化,然后定义两个方法perimeter和area求三角形的周长、面积。在main()中创建一个Triangle类的对象,求给定三个点的三角形的周长、面积。
时间: 2023-06-20 09:08:21 浏览: 82
C++课程设计之三角形的种类和面积
好的,以下是代码实现:
```python
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Triangle:
def __init__(self):
self.point1 = Point()
self.point2 = Point()
self.point3 = Point()
def setPoints(self, x1, y1, x2, y2, x3, y3):
self.point1.x = x1
self.point1.y = y1
self.point2.x = x2
self.point2.y = y2
self.point3.x = x3
self.point3.y = y3
def sideLength(self, p1, p2):
return ((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2) ** 0.5
def perimeter(self):
return self.sideLength(self.point1, self.point2) + self.sideLength(self.point2, self.point3) + self.sideLength(self.point3, self.point1)
def area(self):
a = self.sideLength(self.point1, self.point2)
b = self.sideLength(self.point2, self.point3)
c = self.sideLength(self.point3, self.point1)
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
# 创建Triangle对象并设置三个点的坐标
t = Triangle()
t.setPoints(0, 0, 3, 0, 0, 4)
# 计算周长和面积并输出结果
print("Triangle perimeter:", t.perimeter())
print("Triangle area:", t.area())
```
运行结果:
```
Triangle perimeter: 12.0
Triangle area: 6.0
```
阅读全文