今天看Effective java中有這么一條"如果要求精確答案,請避免使用float和double".
這可真讓我大吃一驚!!我很不解,而且不是很相信.于是我寫了兩個個程序試驗了下.

 1public class TestFloatDouble {
 2
 3    public static void main(String[] args) {
 4
 5        float a = (float1.03;
 6        float b = (float) .42;
 7        
 8        double c = 1.03;
 9        double d = .42;
10        
11        System.out.println(a * b);
12        System.out.println(c - d);
13    }

14
15}

輸出結果為
0.43259996
0.6100000000000001

而正確結果應為
0.4326
0.61


如果需要得到精確答案,那就用java.math里的BigDecimal吧,雖然效率相對低一點,但至少是正確的!!!
 1import java.math.BigDecimal;
 2
 3public class TestBigDecimal {
 4
 5    public static void main(String[] args) {
 6
 7        BigDecimal a = new BigDecimal("1.03");
 8        BigDecimal b = new BigDecimal(".42");
 9        
10        System.out.println(a.multiply(b));
11        System.out.println(a.subtract(b));
12        
13    }

14
15}

輸出結果同樣也是正確結果為
0.4326
0.61

我就不會了,誰能告訴我這是為什么呢???????
各位大蝦們給偶指點下!!!

what the hell is going on ??!!