【发布时间】:2012-05-08 20:15:34
【问题描述】:
可能重复:
strange output in comparision of float with float literal
Why comparing double and float leads to unexpected result?
在下面的代码中,我期望答案是“不相等”,因为默认情况下,3.5 在 C++ 中应该是 double,但结果是“相等”。
声明float a=3.5f和float a=3.5有什么区别?
#include<iostream>
using namespace std;
int main()
{
float a=3.5;
if(a==3.5)
cout<<"equal"<<endl;
else
cout<<"Not equal"<<endl;
return 0;
}
【问题讨论】:
-
尝试创建一个双精度和浮点数,它们都等于 1.0/3.0,然后看看它们是否相等。你会发现他们不是。
-
是的 Benj 我明白你的意思。你的意思是说这些是不相等的,因为精度。
-
在比较浮点值是否相等时,我总是使用:fabs(v1-v2)
标签: c++ floating-point number-formatting