This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
                                
                                    (14个回答)
                                
                        
                5年前关闭。
            
        

有人可以解释为什么z的结果等于12吗?
我已经读过关于前后增量的信息,但是这里的这个对我来说仍然没有意义。

public static void main(String[] args) {
        int x = 1, y = 2, z = 3;
        x = x + y;
        y = y + x;
        z = z + (x++) + (++y);
        System.out.print("x = " + x + "\ny = " + y + "\nz = " + z);
     }
}


就像我看到的那样:

x = x + yx-> 1(后加1)+ y-> 3(前加1),x = 4

y = y + xy-> 4(再次预加1)+ x-> 2(后加1),y = 6

z = z + (x++) + (++y)z-> 3 + x-> 3(后加1)+ y-> 5(前加1),z = 11

最佳答案

y = x++; // This assignes x 's value to y then increment x by 1
y = ++x; // This increments x by one then assigns new x's value to y.


在你的代码上

    int x = 1, y = 2, z = 3;
    x = x + y;
    // x = 3
    y = y + x;
    // y = 5
    z = z + (x++) + (++y);
    // z = 3 + 3 + 6 --> 12


z = z + (x++) + (++y);代码等于以下3行代码的组合:

y = y + 1;
z = z + x + y;
x = x + 1;

09-10 21:56