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

在以下程序中,表达式评估完成后立即使用后增量运算符。现在对于第一个程序,答案不应该是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。

最佳答案

如果您同时分析语句的执行方式和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


这是因为两个增量运算符是按顺序求值的,因此第二个看到了第一个的效果。

关于java - 增量减量运算符的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45370269/

10-10 22:54