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
精彩评论