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

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

伊谢尔伦
伊谢尔伦

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

全部回复(3)
大家讲道理

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一样了。

原因

黄舟

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

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。

伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!