0
    public static void main(String[] args) {
    int a = 1;
    int b = a++;

    System.out.println(b);
}

为什么上面的代码打印 1?有人告诉我 a++ 意味着你会得到 a 的值。然后增加它。但是上面的代码从来没有增加a,只是打印了1。有人可以解释一下这里发生了什么吗?

4

5 回答 5

4

它按预期工作;这是解释的代码:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // b is assigned the value of a (1) and THEN a is incremented.
    // b is now 1 and a is 2.
    int b = a++;

    System.out.println(b);
    // if you had printed a here it would have been 2
}

这是相同的代码,但预先增加了 a:

public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // a is incremented (now 2) and THEN b is assigned the value of a (2) 
    // b is now 2 and so is a.
    int b = ++a;

    System.out.println(b);
    // if you had printed a here it would have been 2 so is b.
}
于 2013-11-14T05:21:50.380 回答
0

int b = a++相当于int b = a; a += 1。打印b时,a==2 && b==1

于 2013-11-14T05:21:24.230 回答
0

a++ 就像说- 然后aa1。所以在你说b = a++b = 1之后a = 2

如果您要 preincrement b = ++a,您将b = 2在分配值之前获得 Preincrement 增加。

结论

a++ 在递增之前赋值
++a 递增,然后赋值。

于 2013-11-14T05:23:35.183 回答
0
The reason is is as follow.

If it is i++, then equalent code is like this.

result = i;
i = i+1;
return result


If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i

So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)
于 2013-11-14T05:23:52.830 回答
0

后增量含义=首先完成分配然后增量。预增量含义=首先增量然后分配。

前任:

int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1

如果

int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1
于 2013-11-14T05:33:12.780 回答