1
後增的行爲
有人能解釋一下下面的代碼執行:預增和在Java中
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.這是怎麼發生的?
確定。但是,那麼我無法理解在以下頁面中操作符優先級的含義: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – 2015-03-03 12:12:13
@Karşıbalıeach「sub expression」('j - ','++ j','j ++')從左到右進行評估。一旦每個子表達式都被評估過,它們將根據優先規則進行「組合」,以便計算「temp 2/temp3」,然後將其添加到「temp1」 - 沒有預定規則,「temp1」將被添加到「 temp2',結果將被除以temp3 ... – assylias 2015-03-03 12:19:00