比较两个double或两个float值的最有效方法是什么?
简单地这样做是不正确的:
bool CompareDoubles1 (double A, double B)
{
return A == B;
}
Run Code Online (Sandbox Code Playgroud)
但是像这样:
bool CompareDoubles2 (double A, double B)
{
diff = A - B;
return (diff < EPSILON) && (-diff < EPSILON);
}
Run Code Online (Sandbox Code Playgroud)
似乎浪费处理.
有谁知道更聪明的浮动比较器?
float f = 0.7;
if( f == 0.7 )
printf("equal");
else
printf("not equal");
Run Code Online (Sandbox Code Playgroud)
为什么输出not equal?
为什么会这样?
我有一个double打印出来0.000000,我试图比较它0.0f,但没有成功.为什么这里有区别?什么是最可靠的方法来确定你的双倍是零?
int a = 8;
if (a==8)
printf("x");
else
printf("y");
Run Code Online (Sandbox Code Playgroud)
虽然a等于8,但它输出y.