我有一个算法的 C 代码,用于检查给定点是否在多边形内。它应该是正确的,我还在各个地方看到这个代码。然而,当我使用它时,它并不能完美地工作——大约 20% 的答案是错误的。
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;
}
也许我的主要功能有问题。有人可以给我一个主要功能来检查这个算法吗?
这是我的主要功能
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;
}