我知道Java中的Math.pow
方法返回double
。但这段代码并没有在我的程序中产生任何错误。编译器是否自动将 (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
。
关于JAVA类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814320/