JAVA类型转换 [英] JAVA type conversion

查看:129
本文介绍了JAVA类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that Math.pow method return double in java. But this code did not generate any error in my program. Does the compiler automatically add (int) to my code, or there is any other reason?

代码之前,我宣布
int sum = 0;和arg是int的数组。

Before the code, I declared that int sum = 0; and arg is array of int.

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


推荐答案

根据 jls-5.6.2 Binary Numeric Promotion


如果任一操作数的类型为double,则另一个操作数转换为double。

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

表达式变为 int + = double ,并且根据 jls-15.26.2复合赋值运算符

the expression becomes int += double, and according to jls-15.26.2 Compound Assignment Operators:


二元操作的结果转换为
左手变量的类型

结果最终转换为 int

这篇关于JAVA类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆