JAVA类型转换

标签 java type-conversion int double type-narrowing

我知道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/

相关文章:

java - 这个等待通知线程语义的真正目的是什么?

java - 使用 Java 使用 REST API

C 将文字 char '0' 转换为 int 0(零),如何?

mysql - 在 MySQL 中将存储的 md5 字符串转换为十进制值

java - 显示表: titlekey not working

java - 如何使用 JSP 和 Servlet 从 String 和 List<String> 的映射动态生成表?

python - 使用 Python C-API 强制类型转换

c++ - 发送和接收 int C++

objective-c - 将 float 四舍五入到 objective-c 中的下一个整数?

python - 如何将 2D 字符串列表转换为 2D int 列表 python?