I have this C code of an alogrithm checking whether a given point is inside a polygon. It is supposed to be correct, I also keep seeing this code in various places. However when I use it doesn't work perfectly - about 20% of the answers are wrong.
int pnpoly(int nvert, double *vertx, double *verty, double testx, double testy)
{
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
Maybe there is something wrong with my main function. Could somone give me a main function to check this algorthm?
This is my main function
int main(){
double vertx[4] = {10, 10, 0, 0};
double verty[4] = {10, 0, 10, 0};
// for those two it returns "Inside"
double testx = 6;
double testy = 4;
/* for those two it returns "Outside"
double testx = 5;
double testy = 4;
*/
int result = pnpoly(4, vertx, verty, testx, testy);
if (result) {
printf("\nInside\n");
}
else {
printf("\nOutside\n");
}
return 0;
}