2015-07-10 30 views
2
public static void main(String[] args) { 
     final long a= 24 * 60 * 60 * 1000 * 1000; 
     final long b= 24 * 60 * 60 * 1000; 

     System.out.println(a/b); 
} 

它應該返回1000,但返回5爲什麼?Java分區返回不正確的結果

回答

7

24 * 60 * 60 * 100086400000。如果通過1000乘它,它就會溢出int類型(因爲這一個int可以容納的最大價值是214748364786400000000少了很多),你會得到500654080a

然後,當您將結果除以86400000時,您將獲得5

爲了解決這個問題,您需要明確指定乘法結果爲long--這是因爲Java中的所有數值運算符都會產生整數,除非明確指示產生其他數值類型。

在追加對一些操作數的L就足夠了:

final long a = 24 * 60 * 60 * 1000 * 1000L; 
+0

最好在所有文字中使用'L' ...以防萬一它在re之前溢出疼痛的最後一個... – Codebender

+1

@Codebender 24 * 60 * 60 * 1000將永遠不會溢出。 –

+1

在這種情況下,如果表達式是「24000 * 60 * 60 * 1000 * 1000L」,它仍然會溢出...因爲前4個文字將被乘以int。或者讓第一個很長......不是最後一個...... – Codebender

1

java中考慮爲int的純數。您需要附加L以轉換爲long。沒有La =500654080,這是錯誤的。

final long a= 24 * 60 * 60 * 1000 * 1000L;// Append L 
1

24 * 60 * 60 * 1000 * 1000這個原因數值溢出,因爲它會考慮爲int值。所以你會得到奇怪的結果。你應該在這裏使用long

您應該使用24 * 60 * 60 * 1000 * 1000L(這是你如何定義long

How to initialize long in Java?

1

與上述答案同意你可以達到你想要在以下兩個方面的內容:

public static void main(String[] args) { 
     //way 1 
     final long a =(long) 24 * 60 * 60 * 1000 * 1000; 
     final long b = (long)24 * 60 * 60 * 1000; 
     System.out.println(a/b); 
     //way 2 
     final long a1 = 24 * 60 * 60 * 1000 * 1000L; 
     final long b1 = 24 * 60 * 60 * 1000L; 
     System.out.println(a1/b1); 
    } 
0

可以使用的BigInteger或長:

public static void main(String[] args) { 
     final BigInteger a = new BigInteger("24"); 
     //multiply by creating big integers.... 
     final BigInteger b = new BigInteger("60") 

     System.out.println(a.divide(b)); 
}