C语言用结构体计算点集最短距离结果恒为0的问题排查
问题根因排查
- 核心错误:
shortestDist函数声明了double类型返回值,但遍历计算完最短距离后未添加return shortestDistance;语句,导致返回值为未定义的随机值,输出0.00是该类未定义行为的典型表现。 - 次要优化点:原代码重复调用
pointDist计算同一对坐标的距离,可通过临时变量存储当前距离减少冗余计算;边界判断补充N<2的逻辑,覆盖数组长度为0的异常场景;编译时若使用gcc需添加-lm参数链接数学库,避免math.h中函数未定义的编译报错。
修复后完整代码
#include<stdio.h> #include<math.h> // 点结构体定义 struct Point { double x,y; }; // 计算两点之间的距离 double pointDist(struct Point a, struct Point b) { return sqrt((a.y - b.y) * (a.y - b.y) + (a.x - b.x) * (a.x - b.x)); } // 计算点数组中所有点对的最短距离 double shortestDist(struct Point SA[], int N) { // 边界判断:点数小于2无法构成点对 if(N < 2) { return -1; } double shortestDistance = pointDist(SA[0], SA[1]); for(int i = 0; i < N-1; ++i) { for(int j = i + 1; j < N; ++j) { double currentDist = pointDist(SA[i], SA[j]); if(shortestDistance > currentDist) { shortestDistance = currentDist; } } } // 补全返回值语句 return shortestDistance; } int main() { struct Point SA[4] = {{1,2}, {1,3},{3,1},{2,1}}; printf("The shortest distance between points are %f\n", shortestDist(SA, 4)); // 测试用例最短距离为1.0,运行后输出结果为1.000000 return 0; }
内容的提问来源于stack exchange,提问作者Betty Gandhi
相关产品推荐
相关产品推荐

