Why does -103/100 == -2 but 103/100 == 1 in Python? I can't seem to understand why.

有帮助吗?

解决方案

Integer division always rounds down (towards negative infinity).

http://www.mathsisfun.com/numbers/images/round-up.gif

Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the floor1 function applied to the result.

http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations

 

This allows for the integer division and modulo (remainder, %) operators to connect nicely through the identity x == (x/y)*y + (x%y).

 

1  floor(x) is the largest integer not greater than x.

其他提示

Integer division takes (I believe) the floor() of whatever float comes out, more or less.

So that's -2 for the first division and 1 for the second.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top