Find the area of a polygon

Problems that require polygon area are often encountered in computational geometry. Here are some templates.
write picture description here
For the area of ​​the polygon ABCDE, we can regard it as the difference between the areas of the two polygons, that is, Sabcde=Soab+Soae+Soed-Socd-Socb.
According to the cross product of the two-dimensional vector, we can find the area of ​​the triangle oab,
that is, Soab=0.5 *|oa cross product ob|=0.5*|Ax*By-Ay*Bx|. The
same is true.
Sabcde=Soab+Soae+Soed-Socd-Socb
=0.5*|Bx*Ay-By*Ax|+0.5*|Ax*Ey-Ay*Ex|+0.5*|Ex*Dy-Ey*Dx|-0.5* |Dx*Cy-Dy*Cx|-0.5*|Cx*By-Cy*Bx|.
The cross product carries the absolute value. When we remove the absolute value, we will find that the areas of the triangles ocb and odc are negative. That's because the coordinates are given in clockwise order, like OAE, OED, are clockwise, while ODC is counterclockwise.
Therefore, the formula can be simplified.
Sabcde=Soab+Soae+Soed-Socd-Socb
=0.5*(Bx*Ay-By*A.x+Ax*Ey-Ay*E.xE.x*Dy-Ey*D.x+Dx*Cy-Dy *C.x+Cx*By-Cy*Bx).
The following is the code (enter the number of vertices first, and then enter the coordinates of each vertex in the clockwise direction).

/*给出顶点坐标(顺时针输入),求多边形面积*/
#include<stdio.h>
typedef struct{
    double x,y;
}qq;
const int maxn=1e3+7;

double SSS(qq *p,int n)
{
    int s=0;
    for(int i=0;i<n;i++)
    {
        s+=(p[i].x*p[(i+1)%n].y-p[(i+1)%n].x*p[i].y);
    }
    return s/2;
}
int sq(qq *p,int n,int A)
{

}
int main()
{
    qq q[maxn],A;
    int n;
    while(scanf("%d",&n)!=EOF)
    {
//      scanf("%d%d",&A.x,&A.y);
        for(int i=0;i<n;i++)
        {
            scanf("%lf%lf",&q[i].x,&q[i].y);
        }
        double sz=SSS(q,n);
//      int sd=sq(q,n,A);
        printf("%lf\n",sz);
    }
    return 0;
}
/*
3
0 0
0 2
2 0
-2.000000
3
0 0
2 0
0 2
2.000000
*/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324400179&siteId=291194637