Java中的算术运算符(初学者问题)

问题描述:

我知道数组运算符具有优先权。然后是二元关节运算符*,/,%。然后+和 - 它们是低优先级。

I know that array operators have the precedence. Then the binary arthimetic operators * , / , % . Then + and - which they are low precedence.

但是我很困惑在这个例子中哪个将首先解析java。
如果我们有2个运算符具有相同的优先级,那么首先在java中使用哪个运算符?

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?

谢谢。

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.

如果运算符具有相同的优先级,则从左到右对它们进行求值。

If operators have the same precedence then they are evaluated from left to right.

来自教程


当同一优先级
的运算符出现在同一表达式中时,规则
必须治理首先评估。

赋值运算符之外的所有二元运算符从左到右计算
;赋值
运算符从右到左进行计算。

When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

在表达式中, 7/2%5 / 具有相同的优先级,因此从左到右 7/2 = 3 3%5 = 3

In the expression, 7 / 2 % 5, the / and % have the same precedence, so going left to right 7 / 2 = 3 and 3 % 5 = 3.

最高优先级为* /%。以下是您的示例细分:

The highest precedence is given to * / %. Here is the breakdown of your example:

  -2 + 5 * 7 - 7 / 2 % 5
= -2 + (5 * 7) - (7 / 2 % 5)
= -2 + 35 - (3 % 5)
= -2 + 35 - 3
= 30