Python Expressive Puzzlers 3: Long Division
阿新 • • 發佈:2018-12-10
Python Expressive Puzzlers 3: Long Division
長整數的處理在每個程式語言都不同,例如我們會預期底下的Java程式碼會輸出 1000。
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
但是結果卻是5
public class LongDivision {
public static void main(String[] args) {
final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
“Java Puzzlers”一書提醒讀者:「When working with large numbers, watch out for overflow — it’s a silent killer.」
那在 Python 裡呢?
MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000
MILLIS_PER_DAY = 24L * 60 * 60 * 1000
print(MICROS_PER_DAY / MILLIS_PER_DAY)