为什么 24 * 60 * 60 * 1000 * 1000 除以 24 * 60 * 60 * 1000 不等于 Java 中的 1000?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1301368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
提问by Satish
why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
为什么 24 * 60 * 60 * 1000 * 1000 除以 24 * 60 * 60 * 1000 不等于 Java 中的 1000?
回答by Jon Skeet
Because the multiplication overflows 32 bit integers. In 64 bits it's okay:
因为乘法溢出 32 位整数。在 64 位中没问题:
public class Test
{
public static void main(String[] args)
{
int intProduct = 24 * 60 * 60 * 1000 * 1000;
long longProduct = 24L * 60 * 60 * 1000 * 1000;
System.out.println(intProduct); // Prints 500654080
System.out.println(longProduct); // Prints 86400000000
}
}
Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.
显然,在乘法溢出后,除法不会“撤消”溢出。
回答by cherouvim
You need to start with 24L * 60 * ... because the int overflows.
您需要从 24L * 60 * ... 开始,因为 int 溢出。
Your question BTW is a copy/paste of Puzzle 3: Long Divisionfrom Java Puzzlers;)
顺便说一句,您的问题是Puzzle 3: Long Divisionfrom Java Puzzlers的复制/粘贴;)
回答by Thom Smith
If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.
如果要执行该计算,则必须重新排序操作(以避免溢出)或使用更大的数据类型。真正的问题是 Java 中固定大小整数的算术不是结合的。这是一个痛苦,但有一个权衡。

