这个问题简单地归结为2行,第1行将输出1.
std::cout << sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) << std::endl;
然而第二行将输出0,这怎么可能?
std::cout << (sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) == 1) << std::endl;
最小的完整可验证示例:
struct vertice {
double x, y, z;
vertice(double x, double y, double z) {
this->x = x;
this->y = y;
this->z = z;
}
};
void cartDistance(const vertice * a, const vertice * b);
int main() {
cartDistance(new vertice(0, 0, 0), new vertice(0, 0, 1));
system("pause");
return 0;
}
void cartDistance(const vertice * a, const vertice * b) {
std::cout << "dist: " << sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) << std::endl;
std::cout << "dist check: " << (sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) == 1) << std::endl;
}
答案 0 :(得分:2)
流输出操作符正在舍入,因为您并不想看到0.999999999999999999997。数学是不精确的,这是隐藏的。但是,比较运算符确实关心这一点。
浮点运算需要小心。
使用std::setprecision ()
将允许您在小数点后看到更多数字,此时您的问题将更加明显。