7除-3的商和余数分别是多少?

15次阅读

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

JavaNewBoy

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 division

然后行为就跟python3一样了。

原因

xgdgsc

这取决于程序语言设计者对除法、余数运算的定义。

Oberon07语言规定:

The operators DIV and MOD apply to integer operands only. Let q = x DIV 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 DIV (-3) = -2、7 MOD (-3) = 1;(-7) DIV 3 = -3、(-7) MOD 3 = 2。

C语言规定:

When integers are divided, 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。

阳光男孩

python语言里整除默认为向下取整,c系列语言里整除默认为向零取整。是这个原因把。C语言里还规定了A%B的值与A符号一致。

233333333

正文完