我正在尝试围绕质心旋转多边形,但我对公式编码感到困惑。
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
答案 0 :(得分:7)
这是公式:
这可能有点误导,因为公式需要从(x 0 ,y 0 )到(x n-1 ,y n-1 ),但在摘要中包含x n 和y n 的值。你要做的就是环绕列表的开头;即,(x n ,y n )≡(x 0 ,y 0 )。
以下是一些将进行这些计算的代码:
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);