大家讲道理2017-04-17 11:27:15
7/-3 in python2 is first equal to -2.3333333333333335, then round down according to to -3, and then calculate 7%-3 according to the definition of remainder, that is, 7 - ( -3* - 3)= -2. In C (7/-3) is directly throwing away the integer digits , so it is -2, -2 * -3 = 6, 7-6=1. Python3 changed the behavior of this operator, 7/-3 = -2.3333333333333335. Both are correct, but the rounding methods are different.
It is possible in python2
from __future__ import pision
Then the behavior will be the same as python3.
Reason
黄舟2017-04-17 11:27:15
This depends on the programming language designer's definition of division and remainder operations.
Oberon07 language regulations:
The operators p and MOD apply to integer operands only. Let q = x p y, and r = x MOD y. Then quotient q and remainder r are defined by the equation
x = q*y + r 0 <= r < y
This makes 7 p (-3) = -2, 7 MOD (-3) = 1; (-7) p 3 = -3, (-7) MOD 3 = 2.
C language regulations:
When integers are pided, the result of the / operator is the algebraic quotient with any fractional part discarded.
This is often called ''truncation toward zero''.If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.
This makes 7 / (-3) == -2, 7 % (-3) == 1; (-7) / 3 == -2, (-7) % 3 == -1.
伊谢尔伦2017-04-17 11:27:15
The default for integer division in the python language is rounded down, and the default for integer division in the c series language is rounded toward zero. That's the reason. The C language also stipulates that the value of A%B is consistent with the A symbol.