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分區返回不正確的結果
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分區返回不正確的結果
24 * 60 * 60 * 1000
是86400000
。如果通過1000
乘它,它就會溢出int
類型(因爲這一個int
可以容納的最大價值是2147483647
比86400000000
少了很多),你會得到500654080
爲a
。
然後,當您將結果除以86400000
時,您將獲得5
。
爲了解決這個問題,您需要明確指定乘法結果爲long
--這是因爲Java中的所有數值運算符都會產生整數,除非明確指示產生其他數值類型。
在追加對一些操作數的L
就足夠了:
final long a = 24 * 60 * 60 * 1000 * 1000L;
java中考慮爲int
的純數。您需要附加L以轉換爲long
。沒有L
a =500654080
,這是錯誤的。
final long a= 24 * 60 * 60 * 1000 * 1000L;// Append L
24 * 60 * 60 * 1000 * 1000
這個原因數值溢出,因爲它會考慮爲int
值。所以你會得到奇怪的結果。你應該在這裏使用long
。
您應該使用24 * 60 * 60 * 1000 * 1000L
(這是你如何定義long
)
與上述答案同意你可以達到你想要在以下兩個方面的內容:
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);
}
可以使用的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));
}
最好在所有文字中使用'L' ...以防萬一它在re之前溢出疼痛的最後一個... – Codebender
@Codebender 24 * 60 * 60 * 1000將永遠不會溢出。 –
在這種情況下,如果表達式是「24000 * 60 * 60 * 1000 * 1000L」,它仍然會溢出...因爲前4個文字將被乘以int。或者讓第一個很長......不是最後一個...... – Codebender