5
#include<stdio.h>
int main()
{
    float a,b;
    a=4.375;
    b=4.385;

    if(a==4.375)
        printf("YES\n");
    else
        printf("NO\n");

    if(b==4.385)
        printf("YES\n");
    else
        printf("NO\n");

    return 0;
}

此代码的答案:

YES 
NO

我一直在想,如果我将浮点数与双值进行比较。它永远不会匹配它。除非 value 是纯整数。但是这里 float "a" 有 4.375 是准确的,但 "b" 没有

printf("%0.20f\n",a);
printf("%0.20f\n",b);

This prints :

4.37500000000000000000
4.38500022888183593750



but if i print

printf("%0.20f\n",4.475);

It prints 4.47499990463256835938

这种四舍五入的效果如何在某些而不是在其他中显示出来。

谁能解释一下。“WE”应该如何判断浮点变量中的值何时与其中包含的值匹配,何时不匹配?

4

2 回答 2

1

只有当十进制分数可以用二进制分数相加时,从十进制分数到二进制分数的转换才是精确的,如0.5, 0.25, ... 等。

例如在你的情况下

0.375 = 0.25 + 0.125 = 2 -2 + 2 -3

所以它可以用二进制分数精确表示。

Where as the number 0.385 can not be represented by using binary fractions precisely. So numbers like 0.5, 0.25, 0.125, ..., etc. or a combination of these numbers can be represented exactly as floating point numbers. Others like 0.385 will give incorrect results when the comparison or equality operations are performed on them.

于 2013-06-18T10:15:45.163 回答
1

Floating points aren't magic. They contain an exact value and if you compare it with that they will compare equal. The two problems are 1) Some operations are not always entirely exact due to precision issues. If you add one to a float and then subtract one then adding that one might have causes some loss of precision in the least significant value bits and when you subtract it you don't get back to quite the same value you expect. 2) It is not possible to exactly represent every decimal value in the floating point binary format. For example it is not possible to store the exact value of 0.1 in a floating point binary number in exactly the same way that you can't write the value of 1/3.0 as a decimal value exactly no matter how many digits you use.

But in your case if you store a value and compare it with that same value they SHOULD compare equal as they'll both have the same issues in the same way. Your issue though is that you are not comparing like with like. 4.375 and 4.385 are not floats they are doubles and get converted to be stored so when you compare them later it's possible that the converted value is not quite identical. If you write 4.385f and 4.385f to use float values you should get YES both times.

于 2013-06-18T10:16:40.310 回答