简体   繁体   English

Java 中的乘法运算导致负值

[英]Multiplication operation in Java is resulting in negative value

Why does the below calculation produce a negative value?为什么下面的计算会产生负值?

long interval = 0;

interval = ((60000 * 60) * 24) * 30;

Every expression in there is being evaluated (at compile-time, of course; it's a constant) as int * int instead of long * long .那里的每个表达式都被评估(在编译时,当然;它是一个常数)作为int * int而不是long * long The result overflows at some point.结果在某些时候溢出。 So just use L to make all the operand literals long:因此,只需使用L使所有操作数文字变长:

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.当然你可以只做一些操作数长,但我倾向于发现改变一切更容易。

Having said all of this, if you're looking for "30 days-worth of milliseconds" it would be better to use:说了这么多,如果您正在寻找“30 天的毫秒数”,最好使用:

long interval = TimeUnit.DAYS.toMillis(30);

Try this, it won't be negative:试试这个,它不会是负面的:

long interval = 0;

interval = ((60000L * 60L) * 24L) * 30L;

Because the value of the equation is causing a number so big that it wraps around It will result in a Integer.因为方程的值导致了一个非常大的数字,它会环绕它会导致 Integer。Int诠释

Your value is 2592000000 which is bigger than the maximum signed integer value 2^31 (2147483648).您的值是 2592000000,它大于最大有符号 integer 值 2^31 (2147483648)。 This is called integer overflow, the result overflows into negative.这称为 integer 溢出,结果溢出为负。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM