vendredi 6 mars 2015

How do I calculate centroid of a polygon if the vertices of the polygon are given?

http://ift.tt/1wbv17e


I visited the above link and tried to implement the formula to formulate the centroid of a non-self-intersecting closed polygon defined by n vertices (x0,y0), (x1,y1), ..., (xn−1,yn−1).


For instance if the co-ordinates are : (0,1),(1,0),(-1,0) and (0,-1), the resulting co-ordinates of centroid should be :



0.00 0.00



#include<stdio.h>
#include<iostream>
#include<utility>
using namespace std;
int main()
{
int t,points;
scanf("%d",&points);
pair<float,float>p[points];
int i;
for(i=0;i<points;i++)
{
scanf("%f %f",&p[i].first,&p[i].second);

}
float ar,x,y;
for(i=0;i<points-1;i++)
{
ar+=(p[i].first*p[i+1].second-(p[i+1].first*p[i].second));
x+=((p[i].first+p[i+1].first)*ar);
y+=((p[i].second+p[i+1].second)*ar);
}
x/=(3*ar);
y/=(3*ar);
printf("%.2f %.2f\n",x,y);
}


However when I run the above code for the given co-ordinates the resulting co-ordinates of centroid are :



-1.#R -1.#R

Aucun commentaire:

Enregistrer un commentaire