递增递减运算符使用

时间:2017-07-28 09:51:38

标签: java

在以下程序中,在完成表达式评估后立即使用后增量运算符。现在对于第一个程序,答案应该不是40 n然后a的值增加到41.N同样对于程序2,答案应该是41而不是42?

class IncrementDemo{
public static void main(String [] args){ 
    int a=20;
    a= a++ + a++;
    System.out.println(a); //Answer given is 41
}

class IncrementDemo{
public static void main(String [] args){ 
    int a=20;
    a= a++ + ++a; 
    System.out.println(a);
} 

第二个程序给出的答案是42。

5 个答案:

答案 0 :(得分:3)

如果分析语句的执行方式以及同时a的状态,您可以理解行为。

a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
the second a++ is executed, 21 is the result, a = 22
the two results are added, 20 + 21 = 41, a = 41

另一方面,在第二种情况下:

a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
++a is executed, a = 22, 22 is the result
the two results are added, 20 + 22 = 42, a = 42

这是因为两个递增运算符是按顺序计算的,所以第二个看到第一个的效果。

答案 1 :(得分:0)

这两者之间的区别在于,++a将增加a的值并返回递增的值。另一方面,a++将递增值,但返回在递增之前的原始值。

答案 2 :(得分:0)

a = a++ + a++

对于第一个a++,用于计算的a的值是其实际值:20,之后它增加到21。 因此,对于第二个a++,用于计算的值也是a的实际值,但这次它是21,因为它已在第一个a++中递增。

所以你有20 + 21,因此41。

a = a++ + ++a

同样的事情a++a的实际值,20用于计算,然后递增到21。 然后++a,该值在使用之前递增,因此它变为22,然后将其用于计算。

所以你有20 + 22,因此42。

答案 3 :(得分:0)

结果是正确的。

第一种情况

int a=20;
a= a++ + a++;

这导致以下评估步骤:

  • a = a++ + a++a=20
  • a = 20 + a++a=21
  • a = 20 + 21a=22

第二种情况

int a=20;
a= a++ + ++a; 

这导致以下评估步骤:

  • a = a++ + ++aa=20
  • a = 20 + ++aa=21
  • a = 20 + 22a=22

答案 4 :(得分:0)

  

当运算符在前缀模式中使用时,它会增加操作数和   计算该操作数的递增值。用于   后缀模式,它递增其操作数,但计算值为   该操作数在增加之前。

a= a++ + a++;

所以第一次 a ++将产生20,现在一个值变为21

a ++将产生21,所以最终操作返回20 + 21 = 41

类似于第二个程序

 int a=20;
 a= a++ + ++a; 

首先 a ++将产生20,现在价值变为21

第二 ++ a将产生价值22

组合两者将返回结果20 + 22 = 42

相关问题