本文介绍了当使用“加号等于"时,Java为什么要执行从双精度到整数的隐式类型转换?操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码示例A
public class Test {
public static void main(String[] args) {
int i = 0;
i = i + 1.5;
}
}
代码示例B
public class Test {
public static void main(String[] args) {
int i = 0;
i += 1.5;
}
}
毫不奇怪,编译A会产生以下错误.令人惊讶的是,编译B不会产生任何错误,并且看起来就像我在double值1.5之前插入了显式强制转换为integer一样.为什么在世界上会发生这种情况?这违背了我以为我知道的一切!
Unsurprisingly, compiling A produces the error below. Surprisingly, compiling B produces no error and it appears to behave as if I inserted an explicit cast to integer before the double value 1.5. Why in the world does this happen? This goes against everything I thought I knew!
Test.java:6: possible
loss of precision
found : double
required: int
i = i + 1.5;
^
1 error
推荐答案
它按设计工作.复合运算符向该运算符添加隐式强制转换.否则,您必须使用显式强制转换.
It is working as designed. The compound operators add an implicit cast to the operation. Otherwise you have to use an explicit cast.
更多信息?
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
这篇关于当使用“加号等于"时,Java为什么要执行从双精度到整数的隐式类型转换?操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!