java运算符+ =中的隐式转换 [英] implicit conversion in java operator +=
问题描述
我发现java编译对于使用int和float的赋值语句和自我赋值语句有一个非预期的行为。
I've found that java compile has a non-expected behavior regarding assignment and self assignment statements using an int and a float.
下面的代码块说明了错误。
The following code block illustrates the error.
int i = 3;
float f = 0.1f;
i += f; // no compile error, but i = 3
i = i + f; // COMPILE ERROR
-
$ c> i + = f 编译不会发出错误,但是exaluation的结果是一个值为
3
变量i 保持值
3
。In the self assignment
i += f
the compile does not issue an error, but the result of the exaluation is an int with value3
, and the variablei
maintains the value3
.在
i = i + f
表达式中,编译器发出错误:error:possible loss of precision / li>
In the
i = i + f
expression the compiler issues an error with "error: possible loss of precision" message.有人可以解释此行为。
代码块,位于 https://compilr.com/cguedes/java-autoassignment-error/Program.java
推荐答案
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
Java语言规范说:
The Java Language Specification says:
表单的复合赋值表达式
E1 op = E2
等效于E1 =(T)((E1)op(E2))
code> T 是E1
的类型,除了E1
只有一次。A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.因此
i + = f
等效于i =(int)(i + f)
。这篇关于java运算符+ =中的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!