Java 中的算术运算符(初学者问题)
我知道数组运算符具有优先权。然后是二元算数运算符 * 、 / 、 % 。然后 + 和 - 它们的优先级较低。
但我很困惑在这个例子中java首先解决哪个问题。 如果我们有 2 个运算符具有相同的优先级,那么在 java 中哪个运算符将首先使用?
谢谢。
int x = y = -2 + 5 * 7 - 7 / 2 % 5;
如果有人可以为我解决这个问题并向我部分解释。因为这在考试时总是让我感到困惑。
I know that array operators have the precedence. Then the binary arthimetic operators * , / , % . Then + and - which they are low precedence.
But I'm confused which one will java solve first in this example.
And if we have 2 operators have the same priority, what operator will be used first in java?
Thank you.
int x = y = -2 + 5 * 7 - 7 / 2 % 5;
If someone could solve this for me and explain to me part by part. Because this always confuses me in exams.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果运算符具有相同的优先级,则从左到右计算它们。
来自教程:
在表达式
7 / 2 % 5
中,/
和%
具有相同的优先级,因此从左到右7 / 2 = 3
和3 % 5 = 3
。* / % 具有最高优先级。这是您的示例的细分:
If operators have the same precedence then they are evaluated from left to right.
From the tutorial:
In the expression,
7 / 2 % 5
, the/
and%
have the same precedence, so going left to right7 / 2 = 3
and3 % 5 = 3
.The highest precedence is given to * / %. Here is the breakdown of your example:
y
将被赋予值-2 + 5 * 7 - 7 / 2 % 5
。然后x
将被分配y
的值。算术表达式的计算结果如下:
这里对 Java 运算符的解释优先。
y
will be assigned the value of-2 + 5 * 7 - 7 / 2 % 5
. Thenx
will be assignedy
's value.Arithmetic expression will be evaluated like:
Here's an explanation of Java's operator precedence.
这看起来像您需要阅读的内容:Java 运算符教程。
阅读教程,然后自己编写一个示例程序并尝试它,直到您对运算符优先级感到满意为止。这是最好的学习方式。
This looks like what you need to read: Java Operators Tutorial.
Read the tutorial and then write yourself an example program and play around with it until you're happy with operator precedence. It's the best way to learn.
与 / 相同
,* 和 %(乘法)具有相同的优先级,并且它们的关联是从左到右。
+ 和 -(加法)具有相同的优先级,并且它们的关联是从左到右。
乘法运算的优先级高于加法运算。
is same as
/,* and % (multiplicative) are having same precedence and their association is left to right.
+ and - (additive)are having same precedence and their association is left to right.
multiplicative operations are higher precedence over additive operations.
不完全相关,但您可能会对此感兴趣。它与序列点有关,序列点是程序中的点,本质上是编译器确保所有内容同步的点。它之所以出现在 SO 上是因为这个问题“做什么
?”或者更糟糕
为什么会进入无限循环?
< a href="http://www.angelikalanger.com/Articles/VSJ/SequencePoints/SequencePoints.html" rel="nofollow noreferrer">http://www.angelikalanger.com/Articles/VSJ/SequencePoints/SequencePoints.html
Not entirely related, but you may find this of interest. It is to do with sequence points, which are points in a program which are essentially the points where the compiler ensures that everything is synchronised. It arose on SO because of the question what does
do? Or worse
Why does this go into an infinite loop?
http://www.angelikalanger.com/Articles/VSJ/SequencePoints/SequencePoints.html