What determines the sign of m % n for integers?

后端 未结 5 1385
自闭症患者
自闭症患者 2020-12-20 15:36

The modulo in Python is confusing.

In Python, % operator is calculating the remainder:

>>> 9 % 5
4

However:

5条回答
  •  暖寄归人
    2020-12-20 16:01

    Think about it like this:

    0 % 5 is 0

    1 % 5 is 1

    So... what if you go backwards?

    -1 % 5 must be 4

    -2 % 5 must be 3

    and so on.

    You'll see that following this -9 % 5 is 1

    NOTE: Depending on the programming language and the implementation of %, you might get different results since programmers disagree on how to handle negative numbers in %

提交回复
热议问题