C++编写坐标距离计算代码时出现变量未声明及无匹配函数调用错误
C++两点距离计算代码报错修复
报错原因梳理
变量未声明类报错根源
- 结构体定义命名为
Points,后续所有使用的地方均写为Point,拼写不一致导致类型未识别 - 代码多处漏写分号:
float x_portion, y_portion末尾、return sqrt(...)行末尾均缺失分号 - 无效代码未注释:
(x2 - x1)^2、(y2 - y1)^2既不是合法表达式也不是注释,触发语法报错 - main函数内定义了和全局函数同名的float变量
calcDistance,覆盖了函数名,调用时会触发类型错误
无匹配函数调用类报错根源
- 标准库
sqrt函数仅支持1个数值参数,你传入了x_portion、y_portion两个参数,没有匹配的函数重载 - 部分编译器下
math.h的旧C接口和C类型匹配度差,也可能触发调用错误,C推荐使用cmath头文件
修正后完整可运行代码
#include <iostream> #include <cmath> using namespace std; struct Point { float x, y; }; float calcDistance(const Point* num1, const Point* num2) { float x_portion = (num2->x - num1->x) * (num2->x - num1->x); float y_portion = (num2->y - num1->y) * (num2->y - num1->y); return sqrt(x_portion + y_portion); } int main() { Point num1; Point num2; cout << "Enter x and y coordinate for the first point: "; cin >> num1.x >> num1.y; cout << "Enter x and y coordinate for the second point: "; cin >> num2.x >> num2.y; cout << "The distance between two points is " << calcDistance(&num1, &num2) << endl; return 0; }
可选优化建议
- 可以把函数参数改为
const Point&引用类型,不需要传指针也不需要判空,代码更简洁 - 计算平方直接用乘法即可,不需要调用
pow函数,性能更高也避免浮点精度损耗
内容的提问来源于stack exchange,提问作者T0lstoy
相关产品推荐
相关产品推荐

