与增量运算符混淆?

时间:2013-11-24 15:12:04

标签: java

(1)

 int z=0;
 int r=((z++)+z);

这里我想在计算表达式时,变量z的值被认为是1。 但之前;如何更新变量z。

(2)

int y3=0;
int r3=y3=y3++;
System.out.print("(r3+y3)"+"\t"+r3+"\t"+y3);  



here how y3 is still 0 after evaluation of expression y3++, it should have increased by 1.

3 个答案:

答案 0 :(得分:1)

后增量x++是一个表达式,它返回x的值,然后才增加x。

因此:

int y0 = 0;    // y0 is 0
y0 = y0++;     

与:

相同
int y0 = 0;
int x = y0++;     // x = 0, y0=1
y0 = x;           // y0 again 0

答案 1 :(得分:1)

variable++会返回variable原始值。例如:

int variable = 0;
System.out.println(variable++); // 0
System.out.println(variable);   // 1

如果您想要新值,请使用++variable

int variable = 0;
System.out.println(++variable); // 1
System.out.println(variable);   // 1

所以,这是第一个细分的逐步细分:

  1. int z=0; // z is 0 now
  2. int r=((z++)+z);
  3. int r=(0+z); // z is 1 now
  4. int r=(0+1);
  5. int r=1;
  6. 第二个:

    1. int y3=0; // y3 is 0 now
    2. int r3=y3=y3++;
    3. int r3=y3=0; // y3 was incremented to 1, but then we immediately set it back to 0

答案 2 :(得分:1)

只需遵循以下规则:x++首先按x递增1,然后返回值。

(1)

        int z = 0;
        int r = z++ + z;
Step1:      r = 0 + z; z = 1;
Step2:      r = 0 + 1;
Step3:      r = 1;

(2)

        int y3 = 0;
        int r3 = y3 = y3++;
Step1:      y3 = 1; // New value by increment
Step2:      y3 = 0; // Old value
Step3:      r3 = y3;