如果我有以下代码:
long interval = 0;
interval = ((6000 * 60) * 24) * 30;
它不会运行,因为我需要将每个文字都设为Long.这样可行:
interval = ((6000L * 60L) * 24L) * 30L;
但是,如果我试图将char类型中的不同变量相乘呢?说我有:
char a, b, c, d;
我给这些字符中的每个字符赋值,所以我尝试:
interval = a * b * c * d;
如果这个溢出,我不能只放L,因为这会调用不同的变量.
interval = aL * bL * cL * dL;
我已尝试将这些字符中的每一个转换为很长时间,但该产品仍会返回负数.
解决方法:
Binary numeric promotion is performed on the operands (§5.6.2).
也就是说,对于这种情况,
Otherwise, if either operand is of type long, the other is converted to long.
所以,实际上,你需要的只是在乘法开始时有一个长值.您可以通过几种方式实现这一目标. Either use a cast as demonstrated by Eran.或在表达式中使用长文字
char a, b, c, d;
...
interval = 1L * a * b * c * d;
// (......) result is a long value
通过乘法的开始,我指的是乘法运算符是左关联的这一事实.在您的示例中,如果*的第一个应用程序的结果是long值,它将传播到下一个*.
标签:java
来源: https://codeday.me/bug/20190528/1171850.html