2015-05-13 101 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)完成。

相關問題