The modulo operation on negative numbers in Python

前端 未结 8 1932
无人共我
无人共我 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:59

    I also thought it was a strange behavior of Python. It turns out that I was not solving the division well (on paper); I was giving a value of 0 to the quotient and a value of -5 to the remainder. Terrible... I forgot the geometric representation of integers numbers. By recalling the geometry of integers given by the number line, one can get the correct values for the quotient and the remainder, and check that Python's behavior is fine. (Although I assume that you have already resolved your concern a long time ago).

提交回复
热议问题