java表达式中的后增量

java表达式中的后增量,java,Java,在本例中: int i = 1; while(i < 10) if(i++%2 == 0) System.out.println(i); inti=1; 而(i

在本例中:

int i = 1;

while(i < 10)
    if(i++%2 == 0)
        System.out.println(i);
inti=1;
而(i<10)
如果(i++%2==0)
系统输出打印LN(i);

为什么输出是
3,5,7,9
而不是
2,4,6,8

该条件是在
i
的上一个值上执行的,然后再递增(偶数),但输出是在
i
的递增值上执行的(奇数)。

该条件是在
i
的上一个值上执行的,在递增之前(偶数),但输出是在递增的
i值上完成的(奇数)。

变量后应用的++运算符返回变量的值,并在表达式求值后递增变量。语义与此相同:

int i = 1;
while(i < 10) { 
    boolean cond = i % 2 == 0;
    i = i + 1;
    if(cond) {
        System.out.println(i);
    }
}
inti=1;
而(i<10){
布尔条件=i%2==0;
i=i+1;
如果(秒){
系统输出打印LN(i);
}
}

变量后应用的++运算符返回变量的值,并在计算表达式后递增变量。语义与此相同:

int i = 1;
while(i < 10) { 
    boolean cond = i % 2 == 0;
    i = i + 1;
    if(cond) {
        System.out.println(i);
    }
}
inti=1;
而(i<10){
布尔条件=i%2==0;
i=i+1;
如果(秒){
系统输出打印LN(i);
}
}

增量后运算符在表达式中使用其操作数的当前值,然后对其进行增量

例如,我们可以使用文本值“2”来分解它。 基本上这就是您当前的代码所做的:

int i = 2;

if (i % 2 == 0) //true, 2 % 2 = 0
    i = i + 1;  //i now becomes 3
    System.out.println (i);  
或者更简单一点,如果我们删除循环并放回代码

int i = 1;

if (i++ % 2 == 0) //1 % 2 != 0 

   System.out.println (i);  //Nothing will print for the if statement

   System.out.print i;  //Will print 2, because this print statement is outside
                        //the body of the if-statement
要获得所需的输出,必须使用前缀增量运算符(++i)

这相当于

 int i = 1
 if ( (i + i) % 2 == 0) //++i increments i and then uses it in the expression
      System.out.println (i);

增量后运算符在表达式中使用其操作数的当前值,然后对其进行增量

例如,我们可以使用文本值“2”来分解它。 基本上这就是您当前的代码所做的:

int i = 2;

if (i % 2 == 0) //true, 2 % 2 = 0
    i = i + 1;  //i now becomes 3
    System.out.println (i);  
或者更简单一点,如果我们删除循环并放回代码

int i = 1;

if (i++ % 2 == 0) //1 % 2 != 0 

   System.out.println (i);  //Nothing will print for the if statement

   System.out.print i;  //Will print 2, because this print statement is outside
                        //the body of the if-statement
要获得所需的输出,必须使用前缀增量运算符(++i)

这相当于

 int i = 1
 if ( (i + i) % 2 == 0) //++i increments i and then uses it in the expression
      System.out.println (i);