本文介绍了浮点数与C中值的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b 1)


$ b $在C中遇到了两个程序,它们都是比较浮点数的, b

  

既然 double 宽于 float , x == 0.1 被解释为<$

这个函数对于0.5来说是可以的,因为0.5在二进制文件中是精确表示的,所以(double)0.5f 精确地产生0.5。另一方面,0.1有,0.1f和0.1最后四舍五入成为数字,这些数字在它们所保存的序列的起始数字中有多少不同。

用十进制数表示类比,可以将上面的情况想象为将小数1/3四舍五入到固定的小数位数。使用5位有效数字的表示形式,得到0.33333;选择一个10位的结果是0.3333333333。现在,将五位数字投到十位数字结果为0.3333300000,这是不同于0.3333333333的数字。在同样的比喻中,0.5英寸就像十进制的1/10,分别表示为0.10000和0.1000000000,所以可以把它转换成另一个表示,然后不改变它的含义。

如果 x 的内容是从代码设置的标记值,那么简单地将它与 0.1f 而不是 0.1 。如果是计算结果,请参阅,以获取正确比较浮点数量的方法。


I have come across two programs in C, both comparing floating point number but with different outputs.

1)

  #include<stdio.h>
   int main()
   {
       float x = 0.1;
       if (x == 0.1)
           printf("IF");
       else if (x == 0.1f)
            printf("ELSE IF");
       else
            printf("ELSE");
    }

Output : ELSE IF

2)

    int main()
   {
       float x = 0.5;
       if (x == 0.5)
           printf("IF");
       else if (x == 0.5f)
            printf("ELSE IF");
       else
            printf("ELSE");
    }

Output : IF

why 0.5 is not promoted to double whereas 0.1 is?

解决方案

Since double is wider than float, x == 0.1 is interpreted as (double) x == 0.1.

This works for 0.5 because 0.5 is exactly representable in binary, so (double) 0.5f produces precisely 0.5. On the other hand, 0.1 has an infinite-digit representation in binary, and 0.1f and 0.1 end up being rounded to numbers that differ in how many initial digits of the sequence they hold.

In an analogy with decimal numbers, you can think of the above situation as trying to write down the fraction 1/3 by rounding it to a fixed number of decimal digits. Using a 5-significant-digit representation, you get 0.33333; choosing a 10-digit one results in 0.3333333333. Now, "casting" the five-digit number to ten digits results in 0.3333300000, which is a different number than 0.3333333333. In the same analogy, 0.5 in is like 1/10 in decimal, which would be represented as 0.10000 and 0.1000000000 respectively, so one could convert it to the other representation and back without changing its meaning.

If the contents of x is a marker value set from code, then simply compare it to 0.1f instead of to 0.1. If it is the result of a calculation, see Paul's answer for the correct way to compare floating-point quantities.

这篇关于浮点数与C中值的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:43