2015-05-13 168 views
1
class MagicWithOperators{ 
    public static void main(String[] args) { 
     float f = 10.2F; 
     double d = 10.2; 
     System.out.println(f==d); 
    } 
} 

产量:false背后的原因是什么

为什么10.2f==10.2是错误的,但10.0f==10.0是真的?

+0

http://stackoverflow.com/a/7392200/4028085 – brso05

回答

2

原因是值10.2无法准确表示,使用floatdouble表示法。两者对10.2的近似值不同,在数学上不相等。

的原因,它的true10.0f10.0是10,可以准确地在这两个floatdouble表示表示。

这里是上述所有数字的十六进制表示。

41233333   // 10.2f (float, inexact) 
4024666666666666 // 10.2 (double, inexact) 
4024666660000000 // 10.2f (widened to double, inexact) 

41200000   // 10.0f (float, exact) 
4024000000000000 // 10.0 (double, exact) 
4024000000000000 // 10.0f (widened to double, exact) 

的转换与Integer.toHexString(Float.floatToIntBits())Long.toHexString(Double.doubleToLongBits)完成。

相关问题