Java num=+10 和 num+=10 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20584409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between num=+10 and num+=10?
提问by user3102361
I am new to java, so while experimenting (which is, as you know, the best way to learn), I tried the following code:
我是 Java 新手,因此在进行实验时(如您所知,这是最好的学习方式),我尝试了以下代码:
public class wHilE{
public static void main(String[] args){
int num = 10;
while(num<=100){
System.out.println("while countdown = "+ num);
num=+10;
}
}
}
It results is an infinite loop printing while countdown = 10
, but when I change num=+10
to num+=10
I get the desired result.
结果是无限循环打印while countdown = 10
,但是当我更改为时num=+10
,num+=10
我得到了想要的结果。
Why is it so?
为什么会这样?
回答by dasblinkenlight
The +=
is a compound assignment; the =+
is a normal assignment, followed by a plus sign, which is optional for positive numbers:
的+=
是这样的化合物分配; the=+
是正常赋值,后跟一个加号,对于正数是可选的:
x += 10;
^ ^^ ^^
| | |
var | val
compound assignment
vs.
对比
x = +10;
^ ^ ^^^
| | |
var| val
assignment
The first operation adds ten to x
; the second operation assigns 10 to x
regardless of its prior value.
第一个操作将 10 添加到x
; 第二个操作将 10 分配给x
不管它的先前值。
回答by Eran
num=+10
is equivalent to num=10
. That's why the loop never ended.
num=+10
相当于num=10
。这就是循环从未结束的原因。
num+=10
is equivalent to num=num+10
, which gives you the desired behavior.
num+=10
相当于num=num+10
,它为您提供所需的行为。
回答by ronilp
num += 10
means num = num + 10
It will assign num + 10 value to num.
num += 10
意味着num = num + 10
它将为 num 分配 num + 10 值。
Whereas num=+10
means num = +10
which means +10 value will be stored in num.
+10 here means positive 10.
而num=+10
意味着num = +10
这意味着 +10 值将存储在 num 中。+10 这里的意思是正 10。