簡體   English   中英

我想根據寫入的點數計算形成的多邊形的面積,前提是最多4個點

[英]I want to calculate the area of the polygon formed according to the number of points written, provided that it is a maximum of 4 points

我想根據寫入的點數計算形成的多邊形的面積,前提是最多4個點。

import math

class Point: #This class is correct
    def __init__(self, x, y):
        self.x = x
        self.y = y


point1 = Point(int(input()), int(input()))  # Point(x,y)
point2 = Point(int(input()), int(input()))


def to_point(point1: Point, point2: Point):
    res = math.sqrt(((point1.x - point2.x) ** 2) + ((point1.y - point2.y) ** 2))
    return res

print(to_point(point1, point2))

我在使用下面的代碼時遇到問題。

class Polygon(Point):
    def __init__(self):
        super().__init__(self.x,self.y)

point_a=Point(int(input()),int(input()))
point_b = Point(int(input()), int(input()))
point_c = Point(int(input()), int(input()))
point_d= Point(int(input()), int(input()))

def get_Area(self,point_a: Polygon,point_b:Polygon,point_c: Polygon,point_d:Polygon):
    print("Enter the number of point")
    n=int(input())
    if n==2:
        print(to_point(point_a, point_b))
    elif n==3:
        return abs(((point_a.x*point_b.y)+(point_b.x*point_c.y)+(point_c.x*point_a.y))-((point_b.x*point_a.y)+(point_c.x*point_b.y)+(point_a.x*point_c.y)))*0.5
    elif n==4:
        return #I can't calculate area for 4 points
print(get_Area(point_a,point_b,point_c,point_d)) '''

嘗試這個:

elif n==4:
    return abs((point_a.x*point_b.y - point_a.y*point_b.x) +
               (point_b.x*point_c.y - point_b.y*point_c.x) + 
               (point_c.x*point_d.y - point_c.y*point_d.x) +
               (point_d.x*point_a.y - point_d.y*point_a.x)) / 2;

它不適用於自相交多邊形,您無法僅用一個公式來表達。 您可以潛在地計算交點並使用三角形公式來計算面積,因為在相交的四邊形中您總是會得到 2 個三角形。 還有一些特殊情況,比如所有點都在一條線上,但這可以通過清理輸入來解決。

查看https://www.mathopenref.com/coordpolygonarea.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM