如何在C语言中计算多边形的重心

3

我正在尝试围绕多边形的重心进行旋转,但是我对公式编码感到困惑。

float x[32];
float y[32];
float cx=0;
float cy=0;
int j,n;
printf("How many angles :")
scanf("%d" ,&n);
//get (x[j],y[j]);
for (j=0; j<n; j++){
printf("x%d : ",j+1);
scanf("%f" ,&x[j]);
printf("y%d : ",j+1);
scanf(input, "%f" ,&y[j]);
}
//find a
//find cx
//find cy
printf("The centroid of the polygon is (%f,%f)",cx,cy);

多边形重心公式
http://i.stack.imgur.com/qjezn.png


请参考以下链接:https://dev59.com/-nE85IYBdhLWcg3wZyqt - chux - Reinstate Monica
1个回答

8
这是公式: Wikipedia formula for centroid of polygon 这个公式可能有点误导性,因为它需要一个从(x0,y0)到(xn-1,yn-1)的顶点列表,但包括xn和yn的值在求和中。你需要做的是将其回绕到列表的起始处; 即 (xn,yn) ≡ (x0,y0)。
这里是一些可以进行这些计算的代码:
float a, cx, cy, t;
int i, i1;

/* First calculate the polygon's signed area A */

a = 0.0;
i1 = 1;
for (i=0; i<n; i++) {
  a += x[i] * y[i1] - x[i1] * y[i];
  i1 = (i1 + 1) % n;
}
a *= 0.5;

/* Now calculate the centroid coordinates Cx and Cy */

cx = cy = 0.0;
i1 = 1;
for (i=0; i<n; i++) {
  t = x[i]*y[i1] - x[i1]*y[i];
  cx += (x[i]+x[i1]) * t;
  cy += (y[i]+y[i1]) * t;
  i1 = (i1 + 1) % n;
}
cx = cx / (6.0 * a);
cy = cy / (6.0 * a);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接