java if 语句中 i++ 与 i=i+1 之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30281042/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:49:22  来源:igfitidea点击:

What's the difference between i++ vs i=i+1 in an if statement?

javaif-statement

提问by bwuxiaop

For the 1st code,

对于第一个代码,

int i = 1;
while (i < 10)
    if ((i++) % 2 == 0)
        System.out.println(i);

The system outputs: 3 5 7 9

系统输出:3 5 7 9

For the 2nd code,

对于第二个代码,

int i = 1;
while (i < 10)
    if ((i=i+1) % 2 == 0)
        System.out.println(i);

The system outputs: 2 4 6 8 10

系统输出:2 4 6 8 10

Why are the two outputs different but the formula is the same?

为什么两个输出不同但公式相同?

采纳答案by Timo

If you use i++, the old value will be used for the calculation and the value of iwill 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 = i + 1,情况正好相反:它将首先递增,然后才会进行计算。

If you want to have the behavior of the second case with the brevity of the first, use ++i: In this case, iwill first be incremented before calculating.

如果您希望第二种情况的行为与第一种情况一样简洁,请使用++i: 在这种情况下,i将在计算之前先递增。

For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!

有关更多详细信息和更技术性的解释,请查看赋值、算术和一元运算符文档

回答by Llogari Casas

i = i+1will increment the value of i, and then return the incremented value.

i = i+1将增加 i 的值,然后返回增加的值。

i++will increment the value of i, but return the original value that i held before being incremented.

i++将递增 i 的值,但返回 i 在递增之前持有的原始值。