比较两个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?
为什么会这样?
可能重复:
与float文件相比较的奇怪输出
当我尝试比较2个相同的float值时,它不会在以下代码中打印"相等的值":
void main()
{
float a = 0.7;
clrscr();
if (a < 0.7)
printf("value : %f",a);
else if (a == 0.7)
printf("equal values");
else
printf("hello");
getch();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
可能重复:
C中的浮点问题
#include<stdio.h>
main()
{
int a,b;
float f;
scanf("%2d%3d%4f",&a,&b,&f);
printf("%d %d %f",a,b,f);
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个程序并输入2 4 56.8时,它给出输出2 4 56.799999 .....但我希望2 4 56.8 ....为什么会这样?