【问题标题】:Post and Pre Increment Operator OCJA-1.8后置和前置增量运算符 OCJA-1.8
【发布时间】:2017-11-06 17:40:51
【问题描述】:

我正在练习 java post 和 pre increment 运算符,我对以下程序的输出感到困惑。它是如何生成输出为“8”的?

public class Test{

public static void main(String [] args){
    int x=0;
    x=++x + x++ + x++ + ++x;
    System.out.println(x);
   }    
}

我尝试了更多示例程序,可以在其中跟踪输出

public class Test{
 public static void main(String [] args){
    int x=0;
    x=++x + ++x + ++x + x++;
    //  1 + 2 + 3 + 3 =>9
    System.out.println(x);
  } 
}

【问题讨论】:

标签: java operators post-increment pre-increment unary-operator


【解决方案1】:

这可以说与以下内容相同:

public static void main(String[] args) {
    int x=0;
    int t1 = ++x;
    System.out.println(t1);//t1 = 1 and x = 1
    int t2 = x++;
    System.out.println(t2);//t2 = 1 and x = 2
    int t3 = x++;
    System.out.println(t3);//t3 = 2 and x = 3
    int t4 = ++x;
    System.out.println(t4);//t4 = 4 and x = 4

    x= t1 + t2 + t3 + t4;//x = 1 + 1 + 2 + 4
    System.out.println(x);//8
}

【讨论】:

    【解决方案2】:

    这可能有助于了解操作员前后的行为。

     public class Test{
    
        public static void main(String [] args){
            int x=0;
            x =   ++x   +  x++   +      x++  +     ++ x;
          //0 = (+1+0)  + (1)    + (+1 +1)   + (+1 +1 +2);
          //0  = 1      + 1      +  2      +  4
             System.out.println(x); // prints 8.
           }    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2012-03-07
      • 2012-10-17
      • 1970-01-01
      • 2012-07-11
      • 2011-03-12
      • 2015-08-20
      相关资源
      最近更新 更多