Java中的乘法运算导致负值 [英] Multiplication operation in Java is resulting in negative value
本文介绍了Java中的乘法运算导致负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下计算产生负值?
Why does the below calculation produce a negative value?
long interval = 0;
interval = ((60000 * 60) * 24) * 30;
推荐答案
正在评估其中的每个表达式(在编译时)时间,当然;它是一个常数),因为 int * int
而不是 long * long
。结果在某些时候溢出。所以只需使用 L
使所有操作数文字变长:
Every expression in there is being evaluated (at compile-time, of course; it's a constant) as int * int
instead of long * long
. The result overflows at some point. So just use L
to make all the operand literals long:
interval = ((60000L * 60L) * 24L) * 30L;
当然,只有使一些的操作数长,你才能逃脱,但我倾向于发现更改一切更容易。
Of course you could get away with only making some of the operands longs, but I tend to find it's easier to just change everything.
说完所有这些,如果你正在寻找30天毫秒,它会最好使用:
Having said all of this, if you're looking for "30 days-worth of milliseconds" it would be better to use:
long interval = TimeUnit.DAYS.toMillis(30);
这篇关于Java中的乘法运算导致负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文