我的 C++ 代码中有一个奇怪的错误:
float cosTheta = someFunction();
cout << cosTheta << endl; // prints 1 on the console
if (cosTheta == 1) { // doesn't enter this condition
cout << "it is 1" << endl;
}
float sinTheta = sqrt(1 - pow(cosTheta, 2));
return (someVariable * sinTheta);
问题是:cosTheta是1,但是它没有进入条件,虽然它在屏幕上打印了1。当我打印返回值时,它应该是0,因为cosTheta是1,所以sinTheta得到0,返回值得到0,但是我得到0.0953562...
我在 Java 中测试了相同的代码,结果是 0。
最佳答案
您不应该将 float 与 ==
进行比较。浮点运算中的舍入误差意味着您应该选择精度 EPSILON
(适合您的情况)并像这样使用它:
const float EPSILON = 0.00001;
if( fabs(cosTheta - 1) < EPSILON ) {
cout << "It is approximately 1\n";
}
关于java - 浮点错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870919/