开发者

Java modulus operator - why is the result unexpected?

开发者 https://www.devze.com 2023-02-08 22:40 出处:网络
I understand that in modulus 17/12 = 5. Why 4+17 % 2-1开发者_高级运维 the value is 4, and (4+17) % 2-1 the value is 0?Operator precedence. % is evaluated first, so

I understand that in modulus 17/12 = 5.

Why 4+17 % 2-1开发者_高级运维 the value is 4, and (4+17) % 2-1 the value is 0?


Operator precedence. % is evaluated first, so

4 + 17 % 2 - 1

is equivalent to

4 + (17 % 2) - 1

17%2 == 1 which yields 4+1-1 which equals 4

When you place brackets there, you change the order of evaluation:

(4+17) % 2 - 1

is equivalent to

21 % 2 - 1

which again, because of % having higher precendence than -, yields

1 - 1

which is 0


4+17 % 2-1 is interpreted as 4+(17 % 2)-1 = 4 + 1 -1 = 4 (precedence of % operator is higher than + and -)

(4+17) % 2-1 = 21 % 2 -1 = (21 % 2)-1 = 1-1 = 0

0

精彩评论

暂无评论...
验证码 换一张
取 消