Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

math - Arithmetic Operators in Java (Beginner Question)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

From the tutorial:

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...