3

I'm trying to rotate the polygon around centroid but I confused about coding from formulas.

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);

centroid of polygon formulas
https://i.stack.imgur.com/qjezn.png

nwellnhof
  • 32,319
  • 7
  • 89
  • 113
Barbiyong
  • 147
  • 1
  • 4
  • 14

1 Answers1

8

Here's the formula:

Wikipedia formula for centroid of polygon

It's perhaps a little misleading because the formula requires a list of vertices from (x0,y0) to (xn–1,yn–1), but includes the values of xn and yn in the summations. What you have to do there is wrap around to the start of the list; i.e., (xn,yn) ≔ (x0,y0).

Here's some code that will do these calculations:

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);
r3mainer
  • 23,981
  • 3
  • 51
  • 88