if语句中i ++与i = i + 1的区别是什么? [英] What's the difference between i++ vs i=i+1 in an if statement?
问题描述
对于第一个代码,
int i = 1;
while (i < 10)
if ((i++) % 2 == 0)
System.out.println(i);
系统输出:3 5 7 9
The system outputs: 3 5 7 9
对于第二个代码,
int i = 1;
while (i < 10)
if ((i=i+1) % 2 == 0)
System.out.println(i);
系统输出:2 4 6 8 10
The system outputs: 2 4 6 8 10
为什么两个输出不同但公式相同?
Why are the two outputs different but the formula is the same?
推荐答案
如果您使用 i ++
,旧值将用于计算,之后 i
的值将增加1。
If you use i++
, the old value will be used for the calculation and the value of i
will be increased by 1 afterwards.
对于 i = i + 1
,情况恰恰相反:它将首先递增,然后才会进行计算。
For i = i + 1
, the opposite is the case: It will first be incremented and only then the calculation will take place.
如果您希望第二种情况的行为与第一种情况相同,请使用 ++ i
:In在这种情况下, i
将在计算之前首先递增。
If you want to have the behavior of the second case with the brevity of the first, use ++i
: In this case, i
will first be incremented before calculating.
有关详细信息和更多技术说明,请使用查看分配,算术和一元运算符的文档!
For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!
这篇关于if语句中i ++与i = i + 1的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!