定义多边形类 包含属性:点坐标数组,点数等信息,和三个函数分别为:赋值、求多变形周长函数、求多边形面积函数,用 main() 进行测试。
时间: 2024-06-09 20:07:50 浏览: 60
turf-polygon:基于坐标数组创建一个 geojson 多边形特征。 可以选择添加属性
下面是定义多边形类的代码:
```python
import math
class Polygon:
def __init__(self):
self.vertices = []
self.n = 0
def assign_vertices(self, vertices):
self.vertices = vertices
self.n = len(vertices)
def perimeter(self):
perimeter = 0
for i in range(self.n):
j = (i + 1) % self.n
dx = self.vertices[i][0] - self.vertices[j][0]
dy = self.vertices[i][1] - self.vertices[j][1]
perimeter += math.sqrt(dx * dx + dy * dy)
return perimeter
def area(self):
area = 0
j = self.n - 1
for i in range(self.n):
area += (self.vertices[j][0] + self.vertices[i][0]) * (self.vertices[j][1] - self.vertices[i][1])
j = i
return abs(area / 2)
# 测试代码
if __name__ == '__main__':
polygon = Polygon()
polygon.assign_vertices([(0, 0), (0, 1), (1, 1), (1, 0)])
print("多边形周长为:", polygon.perimeter())
print("多边形面积为:", polygon.area())
```
测试输出:
```
多边形周长为: 4.0
多边形面积为: 1.0
```
阅读全文