The modulo operation on negative numbers in Python

前端 未结 8 1929
无人共我
无人共我 2020-11-22 14:26

I\'ve found some strange behaviour in Python regarding negative numbers:

>>> -5 % 4
3

Could anyone explain what\'s going on?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 14:50

    There is no one best way to handle integer division and mods with negative numbers. It would be nice if a/b was the same magnitude and opposite sign of (-a)/b. It would be nice if a % b was indeed a modulo b. Since we really want a == (a/b)*b + a%b, the first two are incompatible.

    Which one to keep is a difficult question, and there are arguments for both sides. C and C++ round integer division towards zero (so a/b == -((-a)/b)), and apparently Python doesn't.

提交回复
热议问题