【问题标题】:Pre-increment and post-increment behavior in Java [duplicate]Java中的预增量和后增量行为[重复]
【发布时间】:2015-05-03 23:53:09
【问题描述】:

谁能解释一下下面代码的实现:

int j = 1;
System.out.println(j-- + (++j / j++));

我希望输出为 3,如下所述: 由于 '/' 的优先级高于 '+',所以首先计算它。

op1 = ++j (Since it is pre-increment, the value is 2, and j is 2)
op2 = j++ (Since it is post-increment, 2 is assigned and j is incremented to 3)

所以括号内的“/”运算的结果是 2 / 2 = 1。 然后是'+'操作:

op1 = j-- (Since it is Post-increment, the value is 3, and j is decremented to 2)
op2 = 1 (The result of the '/' was 1)

所以,结果应该是 3 + 1 = 4。 但是当我评估这个表达式时,我得到 2。这是怎么发生的?

【问题讨论】:

    标签: java operator-keyword


    【解决方案1】:

    因为“/”的优先级高于“+”,所以首先计算它。

    不,表达式从左到右求值 - 然后使用优先规则关联每个操作数。

    所以你的代码相当于:

    int temp1 = j--; //1
    int temp2 = ++j; //1
    int temp3 = j++; //1
    int result = temp1 + (temp2 / temp3); //2
    

    【讨论】:

    • 好的。但是,然后我无法理解以下页面中运算符存在的含义:docs.oracle.com/javase/tutorial/java/nutsandbolts/…
    • @Karşıbalı 每个“子表达式”(j--++jj++)从左到右进行评估。一旦评估了每个子表达式,它们就会根据优先规则“组合”,因此temp 2 / temp3 被计算出来,然后添加到temp1 - 如果没有优先规则,temp1 将被添加到 temp2 和结果将除以temp3...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2014-12-09
    • 2012-08-22
    • 2015-05-21
    • 2019-03-27
    • 2016-02-02
    相关资源
    最近更新 更多