多边形面积

#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#define eps 1e-8
using namespace std;
struct node
{
    double x,y;
}z;

bool cmp_node(node a,node b)
{
    double ans=(b.x-z.x)*(a.y-z.y)-(b.y-z.y)*(a.x-z.x);
    if(fabs(ans)<eps)
        return sqrt(pow(a.x-z.x,2)+pow(a.y-z.y,2))<sqrt(pow(b.x-z.x,2)+pow(b.y-z.y,2));
    return ans>0;
}
double PolygonArea(node I[],int cnt)
{
    int pos=0;
    double ans=0;
    if(cnt<3)return 0;
    for(int i=0;i<cnt;i++)
    {
        if(I[pos].y>I[i].y)
            pos=i;
        else if(I[pos].y==I[i].y&&I[pos].x>I[i].x)
            pos=i;
    }
    swap(I[pos],I[0]);
    z=I[0];
    sort(I+1,I+cnt,cmp_node);
    for(int i=0;i<cnt;++i)
    {
        ans+=(I[(i+1)%cnt].x*I[i].y-I[(i+1)%cnt].y*I[i].x)/2.0;
    }
    return ans;
}
int main()
{
    node p[5];
    p[0].x=1;p[0].y=5;
    p[1].x=1;p[1].y=3;
    p[2].x=3;p[2].y=1;
    p[3].x=3;p[3].y=3;
    double area=PolygonArea(p,4);
    cout<<area<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/ke-yi-/p/10175818.html