7除-3的商和余数分别是多少?
python2里 7/-3得-3,7%-3得-2 而C里,7/-3得-2,7%-3得1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
python2里 7/-3得-3,7%-3得-2 而C里,7/-3得-2,7%-3得1
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(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里可以
然后行为就跟python3一样了。
原因
这取决于程序语言设计者对除法、余数运算的定义。
Oberon07语言规定:
这就使得7 DIV (-3) = -2、7 MOD (-3) = 1;(-7) DIV 3 = -3、(-7) MOD 3 = 2。
C语言规定:
这就使得 7 / (-3) == -2、7 % (-3) == 1;(-7) / 3 == -2、(-7) % 3 == -1。
python语言里整除默认为向下取整,c系列语言里整除默认为向零取整。是这个原因把。C语言里还规定了A%B的值与A符号一致。