有人可以解释以下代码的实现:
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)
所以' /'的结果在parantheses中的操作是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.为什么会发生这种情况?
答案 0 :(得分:1)
因为' /'优先级高于' +'它首先被评估。
不,表达式从左到右计算 - 然后使用优先规则关联每个操作数。
所以你的代码相当于:
int temp1 = j--; //1
int temp2 = ++j; //1
int temp3 = j++; //1
int result = temp1 + (temp2 / temp3); //2