以下条件背后的原因是什么?

时间:2015-05-13 18:39:54

标签: java operator-keyword

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为真?

1 个答案:

答案 0 :(得分:2)

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

true10.0f 10.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)完成的。

相关问题