python - 7除-3的商和余数分别是多少?
伊谢尔伦
伊谢尔伦 2017-04-17 11:25:15
0
3
2277

python2里 7/-3得-3,7%-3得-2 而C里,7/-3得-2,7%-3得1

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
大家讲道理

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

黄舟

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.

伊谢尔伦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template