Integer division & modulo operation with negative operands in Python

后端 未结 4 575
时光说笑
时光说笑 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条回答
  •  猫巷女王i
    2020-11-27 07:54

    A simple rule: for a % b = c, if c is not zero, then should have the same sign as b.

    And apply the magic formula:

    10 % -3 = -2 => 10 // -3 = (10 - (-2)) / (-3) = -4

    -10 % 3 = 2 => -10 // 3 = (-10 - 2) / 3 = -4

    -10 % -3 = -1 => -10 // -3 = (-10 - (-1)) / (-3) = 3

提交回复
热议问题