Python 中的整数除法
我对 python 中的以下整数数学感到困惑:
-7/3 = -3
因为 (-3)*3 = -9
(-3)*3 = -9
(-3)*3 = -9 < -7 。我明白。
7/-3 = -3
我不明白这是如何定义的。 <代码>(-3)*(-3) = 9 > 7.。在我看来,它应该是-2,因为 (-3)*(-2) = 6
(-3)*(-2) = 6
(-3)*(-2) = 6
(-3)*(-2) = 6 7.
。
这是如何运作的?
I'm confused about the following integer math in python:
-7/3 = -3
since (-3)*3 = -9 < -7
. I understand.
7/-3 = -3
I don't get how this is defined. (-3)*(-3) = 9 > 7
. In my opinion, it should be -2, because (-3)*(-2) = 6 < 7
.
How does this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自文档:
向
-inf
舍入解释了您所看到的行为。From the documentation:
The rounding towards
-inf
explains the behaviour that you're seeing.它是这样工作的:
This is how it works:
扩展 aix 和 robert 的答案。
考虑这一点的最佳方法是对浮点结果进行向下舍入(向负无穷大):
-7/3 = Floor(-2.33) = -3
7/-3 = 下限(-2.33) = -3
Expanding on the answers from aix and robert.
The best way to think of this is in terms of rounding down (towards minus infinity) the floating point result:
-7/3 = floor(-2.33) = -3
7/-3 = floor(-2.33) = -3
/ 用于浮点除法
// 用于整数除法(返回整数)
并且Python将结果向下舍入
/ is used for floating point division
// is used for integer division(returns a whole number)
And python rounds the result down
Python 向下舍入。
7/3 = 2 (2+1/3)
-7/3 = -3 (-2+1/3)
Python rounds down.
7/3 = 2 (2+1/3)
-7/3 = -3 (-2+1/3)