问题描述
我从Java的官方教程中读到前缀和后缀++ - 具有不同的优先级:
I read from the official tutorial of Java that prefix and postfix ++ -- have different precedences:
一元:++ expr --expr + expr -expr~!
unary: ++expr --expr +expr -expr ~ !
根据教程,不应该这个
d = 1; System.out.println(d ++ + ++ d);
打印6( d ++
使d 2, ++ d
使它成为3)而不是4?
print out 6 (d++
makes d 2, ++d
makes it 3) instead of 4?
我知道解释 ++ d
预先评估,但如果 d ++
具有更高的优先级,那么 ++ d
,为什么不首先评估 d ++
?而且,在什么情况下, d ++
表明它具有更高的优先级?
I know the explanation of ++d
being evaluated beforehand, but if d++
has higher precedence then ++d
, why isn't d++
being first evaluated? And what is more, in what case should d++
shows that it has higher precedence?
编辑:
我尝试了以下方法:
d = 1; System.out.println(++ d * d ++);
它返回4.它似乎应该是2 * 2,而不是1 * 3。
It returns 4. It seems that it should be 2*2, instead of 1*3.
推荐答案
println语句的内部是此操作
(d ++)+(++ d)
The inside of the println statement is this operation(d++) + (++d)
- 如下所示,读取d的值(d = 1)
- d(1)的当前值被添加到加法函数中
-
d的值递增(d = 2)。
- It is as follows, the value of d is read (d = 1)
- current value of d (1) is put into the addition function
value of d is incremented (d = 2).
然后,在右侧,读取d的值(2)
Then, on the right side, the value of d is read (2)
最后,将d(3)的值放入加法函数
Finally, the value of d (3) is put into the addition function
因此1 + 3导致4
thus 1 + 3 results in the 4
编辑:对不起格式,我很擅长使用列表哈哈
edit: sorry for the format, I'm rather bad at using the list haha
这篇关于Java中的++和 - 运算符的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!