前后增量,无循环

时间:2014-12-17 16:34:06

标签: java

有人可以解释为什么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(由一人提前),z = 11

3 个答案:

答案 0 :(得分:3)

请参阅下面的代码中的注释。

在问题中你自己的注释的主要问题是你看到没有任何前提增量和后增量运算符。例如,在x = x + y中,这是一个简单的赋值,在任何地方都没有增量。

public static void main(String[] args) {
        int x = 1, y = 2, z = 3;
            // so now (x,y,z) == (1,2,3)
        x = x + y;
            // so now (x,y,z) == (3,2,3)
        y = y + x;
            // so now (x,y,z) == (3,5,3)
        z = z + (x++) + (++y);
            // here, x++ would return 3 (unincremented)
            //       ++y would return 6 (incremented)
            // so now z = 3 + 3 (unincremented x) + 6 (incremented y) == 12
            // and in the process both x and y have been incremented
            // so we have (x,y,z) == (4,6,12)
        System.out.print("x = " + x + "\ny = " + y + "\nz = " + z);
     }
}

答案 1 :(得分:2)

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;

答案 2 :(得分:1)

让我们对z = z + (x++) + (++y);行进行简单的分析(没有实际代码):

z = (previous value of z: 3) + 
    (the existing value of x (increment will take place after the plus expression evaluation): 3 (1 + 2 from previous assign statement)) +
    (the value of y after being incremented by 1: 6 (2 + 3 from previous assign statement + 1 from the increment)). =>
z = 3 + 3 + 6 =>
z = 12 //Assign 12 value to z