用 Python 编写的查找多边形面积的程序
pythonserver side programmingprogramming更新于 2025/12/23 1:48:17
假设我们有一个有序点列表,表示二维平面上的简单多边形端点。我们必须找到这个多边形的面积。
因此,如果输入类似于 points = [(0, 0), (0,5), (3, 5), (3,0)],则输出将为 15。

为了解决这个问题,我们将遵循以下步骤 −
- 定义一个函数 getInfo() 。这将获取 x1、y1、x2、y2
- 返回 x1*y2 - y1*x2
- 从主方法中,执行以下操作
- N := 点的大小
- (firstx, firsty) := points[0]
- (prevx, prevy) := (firstx, firsty)
- res := 0
- 对于范围从 1 到 N-1 的 i,执行
- (nextx, nexty) := points[i]
- res := res + getInfo(prevx, prevy, nextx, nexty)
- prevx := nextx
- prevy := nexty
- res := res + getInfo(prevx, prevy, firstx, firsty)
- 返回 |res| / 2.0
示例
让我们看看下面的实现以便更好地理解 −
def getInfo(x1, y1, x2, y2): return x1*y2 - y1*x2 def solve(points): N = len(points) firstx, firsty = points[0] prevx, prevy = firstx, firsty res = 0 for i in range(1, N): nextx, nexty = points[i] res = res + getInfo(prevx,prevy,nextx,nexty) prevx = nextx prevy = nexty res = res + getInfo(prevx,prevy,firstx,firsty) return abs(res)/2.0 points = [(0, 0), (0,5), (3, 5), (3,0)] print(solve(points))
输入
[(0, 0), (0,5), (3, 5), (3,0)]
输出
15.0
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

