Python Code
print (-7%2) #1
print(-7%3)#2
print(7%-2)#-1
print(-7%3)#2
print(7%-3)#-2
But don't you know why?
python
The reason is, "That's what I decided to do."Specification: The division of integers is rounded in a negative infinite direction.
(2)
Also, if (x//y)*y+(x%y)=x
is not present, the remainder will inevitably be determined.
This behavior shows questions tagged with c or python, this is the decision you made.
# I want to know why Oira decided to do so.
First of all, Python interprets the monomial minus -
over %
as priority, so for example -7%2
is not (-7)%2
.
Python's remainder operator %
returns the remainder of the second argument and the same symbol.Therefore, (-7)%2
returns 1
, while 7%(-2)
returns -1
.
*Supplement: Why -7%3
is 2
This is about mathematics before Python, but if you write -7=3*(-3)+2, the remainder is 2.
You can also take -7=3*(-2)-1 and make the remainder -1, which gives you a choice.
Similarly, there are several ways that 7%-3
and -7%-3
can be handled in a uniform manner, and different languages can be used in different ways.
© 2025 OneMinuteCode. All rights reserved.