2015-03-03 44 views
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.這是怎麼發生的?

回答

1

由於'/'的優先級高於'+',因此首先進行評估。

不,從左到右評估表達式 - 然後使用優先規則關聯每個操作數。

所以,你的代碼就相當於:

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

確定。但是,那麼我無法理解在以下頁面中操作符優先級的含義: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – 2015-03-03 12:12:13

+0

@Karşıbalıeach「sub expression」('j - ','++ j','j ++')從左到右進行評估。一旦每個子表達式都被評估過,它們將根據優先規則進行「組合」,以便計算「temp 2/temp3」,然後將其添加到「temp1」 - 沒有預定規則,「temp1」將被添加到「 temp2',結果將被除以temp3 ... – assylias 2015-03-03 12:19:00