我正在用 python 编写代码:
1 / -2
结果不是0而是-1,我糊涂了。为什么python要这样设计?其背后的逻辑是什么?
我正在使用 python 2.7.6
请您参考如下方法:
Guido 自己在这里解释:http://python-history.blogspot.co.uk/2010/08/why-pythons-integer-division-floors.html .
相关片段:
there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship:
a/b = q with remainder r
such that
b*q + r = a and 0 <= r < b
...
Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.
