Integer division & modulo operation with negative operands in Python

后端 未结 4 556
时光说笑
时光说笑 2020-11-27 07:13

Questions arise when I type in these expressions to Python 3.3.0

-10 // 3  # -4
-10 % 3   #  2
10 // -3  # -4
10 % -3   # -2
-10 // -3 #  3

4条回答
  •  独厮守ぢ
    2020-11-27 08:10

    OK, so I did some digging and I think that the problem isn't Python, but rather the Modulo function. I'm basing this answer off of http://mathforum.org/library/drmath/view/52343.html

    10 % 3 Uses the highest multiple of 3 that is LESS THAN 10. In this case, 9. 10 - 9 = 1

    -10 % 3 does the same thing. It's still looking for a multiple of 3 that is LESS THAN -10. In this case, -12. (-10) - (-12) = 2

提交回复
热议问题