您的位置:首页 > 编程语言 > Go语言

The centre of polygon tzc

2013-05-09 13:50 218 查看
The center of gravity (also known as "center of mass" or "centroid" can be calculated with the following formula:
X = SUM[(Xi + Xi+1) * (Xi * Yi+1 - Xi+1 * Yi)] / 6 / A
Y = SUM[(Yi + Yi+1) * (Xi * Yi+1 - Xi+1 * Yi)] / 6 / A


The centroid of a non-self-intersecting closed polygon defined by n vertices (x0,y0), (x1,y1), ..., (xn−1,yn−1) is the point (Cx, Cy), where





and where A is the polygon's signed area,



becenter实现上述计算

#include<cstdio>
#include<cmath>
struct point
{
double x,y;
}pp[1000008];
point becenter(point pnt[],int m)
{
point p,s;
double tp,area=0,tpx=0,tpy=0;
int i;
p.x=pnt[0].x,p.y=pnt[0].y;
for(i=1;i<=m;i++)
{
s.x=pnt[i%m].x;
s.y=pnt[i%m].y;
tp=(p.x*s.y-s.x*p.y);
area+=tp/2;
tpx+=(p.x+s.x)*tp;
tpy+=(p.y+s.y)*tp;
p.x=s.x;p.y=s.y;
}
s.x=tpx/(6*area);
s.y=tpy/(6*area);
return s;
}
int main()
{
int i,j;
double l,k,d,n;
int ncase,m;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d",&m);
for(i=0;i<m;i++)
scanf("%lf%lf",&pp[i].x,&pp[i].y);
point c=becenter(pp,m);
printf("%.2lf %.2lf\n",c.x,c.y);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: