// Construct an array of length MAX_POINTS.
// Populate the array with given points and initialize the number points being handled.
// Print the given points for the user.
struct Point points[MAX_POINTS];
int numPoints = readPoints(points);
printf("Set of points: \n");
displayPoints(points, numPoints);
// Construct an array to represent the hull with max possible points (numPoints).
struct Point hull[numPoints];
struct Point pointOnHull = leftmostPoint(points, numPoints);
struct Point endPoint;
int e = 0;
// Perform Jarvis March.
do {
hull[e] = pointOnHull;
endPoint = points[0];
for ( int i = 1; i < numPoints; i++ )
if ( (endPoint == pointOnHull) || (ccw(hull[e], endPoint, points[i]) > 0) )
endPoint = points[i];
++e;
} while ( endPoint != hull[0] ); // we've looped back to the beginning.
// Print the mapped hull points.
printf("Convex hull: \n");
displayPoints(hull, numPoints);
这是我用于解决凸包的Jarvis March(礼品包装)程序的代码。 GCC在我的struct point比较(endPoint == pointOnHull
和endPoint != hull[0])
上都会出错。我是C的新手,这是我正在做的第一个用这种语言来做的项目之一。任何人都可以帮我看看我搞砸了吗?
具体错误:
jarvis.c:31:19:错误:无效操作数到二进制==(有'struct Point'和'struct Point')
jarvis.c:34:21:错误:二进制操作数无效!=('struct Point'和'struct Point')
答案 0 :(得分:2)
C
中的结构没有比较运算符。您必须定义自己的比较函数并使用它来代替==
。尝试这样的事情:
bool equalPoints(const struct Point p1, const struct Point p2) {
return (p1.x == p2.x) && (p1.y == p2.y);
}
if (equalPoints(endPoint, pointOnHull)) { /* then code here */ }
或者如果你的结构更复杂(但事实并非如此):
bool equalPoints(const struct Point *p1, const struct Point *p2) {
/*
* In case your structure is more complex here goes
* more complex comparison code
*/
return (p1->x == p2->x) && (p1->y == p2->y);
}
if (equalPoints(&endPoint, &pointOnHull) { /* then code here */ }
后者不会复制整个Point
结构以将其传递给equalPoints
,而是会传递指针(引用类型)。 const
很重要,因为当您只想比较它们时,它不会让您意外修改点。