JAVA 类型转换

JAVA type conversion

我知道 Math.pow 方法 return double java。但是这段代码并没有在我的程序中产生任何错误。编译器会自动在我的代码中添加(int),还是有其他原因?

在代码之前,我声明了 整数总和= 0; arg 是 int 数组。

for(int i=0; i < arg.length; i++) {
    sum += Math.pow(2, i) * arg[i];
}

根据jls-5.6.2 Binary Numeric Promotion:

If either operand is of type double, the other is converted to double.

表达式变为int += double,根据jls-15.26.2 Compound Assignment Operators

the result of the binary operation is converted to the type of the left-hand variable

结果最终转换为int