叉乘求多边形面积

/*
    叉乘求多边形面积
     http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=3
     给出n个点,围成一个多边形,求该多边形的面积 
*/
# include 
# include 
# include 

using namespace std;

typedef struct Point
{
    double x,y;
}Point;

double Cross(Point A,Point B)
{
    return (A.x * B.y - A.y*B.x)/2.0;
}

int main(void)
{
//  freopen("in.txt","r",stdin);
    int ncase;
    cin >> ncase;
    while(ncase--)
    {
        int n;
        cin >> n;
        Point pt[n+1];
        double Gx=0,Gy=0,ans=0;
        for(int i=0; icin >> pt[i].x >> pt[i].y;
        }
        pt[n].x = pt[0].x; pt[n].y = pt[0].y;

        for(int i=0; i/*
                将多边形上所有的的点与原点相连,构成n-2个三角形
                用叉积求出每个三角形的面积,然后求和,即是整个多边形的面积

            */
            double area = Cross(pt[i],pt[i+1]);
            ans += area;
            /*
                这里要求加权的重心和,重量是均匀分布在多边形上的, 
                所以所以多边形的重心和多边形的面积有关 
                在求每个三角形的重心的时候要乘以三角形面积
                最后多边形的重心再除以多边形面积即可 
            */
            Gx += area*(pt[i].x + pt[i+1].x) / 3;//还有一个原点(0,0) 
            Gy += area*(pt[i].y + pt[i+1].y) / 3;
        }
        ans = fabs(ans);
        if(ans < 0.00000001)
            cout << "0.000 0.000"<else
            printf("%.3lf %.3lf\n",ans,fabs(Gx+Gy)/ans);        
    }

    return 0;
 } 

你可能感兴趣的:(叉乘求多边形面积)