大家讲道理2017-04-17 11:27:15
python2裡的7/-3先是等於-2.3333333333333335,然後按照向下取整為-3,然後按照餘數的定義計算7%-3,即7 - ( -3* - 3)= -2. C裡(7/-3)是直接丟掉整數位後的位所以為-2,-2 * -3 = 6,7-6=1. python3改變了這個運算子的行為,7/-3 = -2.3333333333333335。 都沒有錯,只不過取整的方法不一樣。
python2裡可以
from __future__ import pision
然後行為就跟python3一樣了。
原因
黄舟2017-04-17 11:27:15
這取決於程式語言設計者對除法、餘數運算的定義。
Oberon07語言規定:
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
這使得7 p (-3) = -2、7 MOD (-3) = 1;(-7) p 3 = -3、(-7) MOD 3 = 2。
C語言規定:
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.
這使得 7 / (-3) == -2、7 % (-3) == 1;(-7) / 3 == -2、(-7) % 3 == -1。