为什么 Java 中的增广赋值运算符会给出不同的结果? [英] Why does the augmented assignement operator in Java give a different result?
问题描述
考虑以下代码:
class 转换器 {公共静态无效主(字符串参数[]){字节数 = 1;数量 = 数量 * 2.5;System.out.println("结果为:" + num);}}
编译器抛出以下错误:
错误:不兼容的类型:第 1 行从双精度到字节的可能有损转换
如果我更改了 main()
方法的第二行并使用了 *=
速记运算符:
类转换器{公共静态无效主(字符串参数[]){字节数 = 1;数量 *= 2.5;System.out.println("结果为:" + num);}}
代码编译并成功运行,输出:
结果是:2
为什么 *=
速记运算符与完整表达式 num = num * 2.5
的行为不同?
来自 JLS 复合赋值运算符 文档,你可以看下面的例子:
<块引用>例如下面的代码是正确的:
short x = 3;x += 4.6;
<块引用>
并导致 x 的值为 7,因为它等价于:
short x = 3;x = (短)(x + 4.6);
默认情况下它只是自动转换结果.
PS:在这个其他答案 我试图解释您需要使用 JLS 进行如下操作的原因
short x = 3;x = x + 1;//不会编译
它是全新的,所以我乐于接受建议.
Consider the following piece of code:
class Converter {
public static void main(String args[]) {
byte num = 1;
num = num * 2.5;
System.out.println("Result is: " + num);
}
}
The compiler throws the following error:
error: incompatible types: possible lossy conversion from double to the byte at line 1
If I change the second line of the main()
method and I use the *=
shorthand operator:
class Converter {
public static void main(String args[]) {
byte num = 1;
num *= 2.5;
System.out.println("Result is: " + num);
}
}
The code compiles and runs successfully with the output:
Result is: 2
Why the *=
shorthand operator is behaving differently from the full expression num = num * 2.5
?
From the JLS compound assigment operator documentation, you can see the following example :
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
It simply auto cast the result by default.
PS : In this other answer I tried to explain the reason you need to cast an operation like the following using the JLS
short x = 3;
x = x + 1; //Won't compile
It is realativly new so I am open to suggestion there.
这篇关于为什么 Java 中的增广赋值运算符会给出不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!