What determines the sign of m % n for integers?

后端 未结 5 1389
自闭症患者
自闭症患者 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:07

    -10 % 5 is 0, ie, -10 is evenly divided by 5.

    You ask why -9 % 5 is not -4, and the answer is that both 1 and -4 can be correct answers, it depends on what -9 divided by 5 is. Of course -9 divided by 5 is 1.8, but this is integer division, in Python 3 represented by //, so I'll use // here to be clear that it's integer division we are talking about.

    I'll explain this by not using negative numbers, it's easier.

    9 // 5 is 1. Ie, you can subtract 5 from 9 only 1 time, and the rest is 4. But if you subtract 5 from 9 one more time, well, then the rest becomes -1!

    So -1 is a correct answer to 9 % 5, if 9 // 5 is 2.

    In Python 9 // 5 is 1, because the Python integer division is a floor division, ie it always rounds down. If it has rounded up 9 // 5 would be two, and 9 % 5 would have been -1.

    Now lets look at the case when we use negative numbers: -9 divided by 5 is now -2. Because it is floor division, it always rounds down. That means that the rest is 1. So -9 % 5 is 1, not -4.

提交回复
热议问题