【问题标题】:What makes the difference is the increment operator ++ comes before the variable or after the variable [duplicate]不同之处在于增量运算符 ++ 出现在变量之前或变量之后 [重复]
【发布时间】:2016-05-19 02:45:51
【问题描述】:

在下面的代码中,当我将 ++ 运算符放在“tos”之后时,我收到一个错误。但是如果我把它放在'tos'之前,代码就会运行。为什么会这样?

void push(int item){
if(tos==9)
    System.out.println("The stack is full");
else
    stck[++tos]=item;
}

【问题讨论】:

    标签: java eclipse


    【解决方案1】:
    • ++tos 表示递增 tos 然后返回 expression 值。
    • tos++ 表示返回 expression 值,然后递增 tos。

    【讨论】:

      【解决方案2】:

      a++ 将返回 a 并递增它,++a 将递增 a 并返回它。

      http://www.sanity-free.com/145/preincrement_vs_postincrement_operators.html

      【讨论】:

        【解决方案3】:

        tos++ 和 ++tos 都会递增它们所应用的变量。 tos++返回的结果是变量自增前的值,而++tos返回的结果是变量应用自增后的值。

        示例:

        public class IncrementTest{
        public static void main(String[] args){
        
        System.out.println("***Post increment test***");
        int n = 10;
        System.out.println(n);      // output  10
        System.out.println(n++);    // output  10
        System.out.println(n);      // output  11
        
        System.out.println("***Pre increment test***");
        int m = 10;
        System.out.println(m);      // output  10
        System.out.println(++m);    // output  11
        System.out.println(m);      // output  11
        }
        }
        

        欲了解更多信息,请阅读:http://www.javawithus.com/tutorial/increment-and-decrement-operators 或 google post increment 和 pre increment in java。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-02
          • 2019-01-28
          • 1970-01-01
          • 1970-01-01
          • 2023-02-15
          • 1970-01-01
          • 1970-01-01
          • 2017-04-18
          相关资源
          最近更新 更多