1 int整數相乘溢出 2 3 我們計算一天中的微秒數: 4 5 long microsPerDay = 24 * 60 * 60 * 1000 * 1000;// 正確結果應為:86400000000 6 System.out.println(microsPerDay);// 實際上為:500654080 7 8 9 問題在於計算過程中溢出了。這個計算式完全是以int運算來執行的,並且只有在運算完成之后,其結果才被提升為long,而此時已經太遲:計算已經溢出。 10 解決方法使計算表達式的第一個因子明確為long型,這樣可以強制表達式中所有的后續計算都用long運算來完成,這樣結果就不會溢出: 11 12 long microsPerDay = 24L * 60 * 60 * 1000 * 1000;