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

发布于 2022-08-25 11:14:12 字数 51 浏览 9 评论 0

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情话难免假 2022-09-01 11:14:12

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

原因

梦冥 2022-09-01 11:14:12

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

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。

疑心病 2022-09-01 11:14:12

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文