负整数除法令人惊讶的结果
在我的应用程序中,我遇到了以下情况,并对结果感到惊讶:
8/-7=-2
(均为整数)。
这意味着什么?
In my application I encountered the following and was surprised by the results:
8/-7=-2
(both integers).
What does this mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于实际值,即
8.0/(-7.0)
,结果大致为-1.143
。使用整数除法的结果将向下舍入到
-2
的更大负值。 (这也称为“楼层除法”)这就是为什么您会得到有些令人困惑的答案:
注意:这是在 Python 3 中“固定”的,其中
8/ 的结果(-7)
将是-1.143
。因此,如果您没有理由使用 Python 2,则应该升级。 ;)在Python 3中,如果您仍然想要整数除法,可以使用
//
运算符。这将为您提供与 Python 2 中的8/(-7)
相同的答案。这是关于该主题的 Python 增强提案:PEP 238 -- 更改除法运算符
For the actual values, i.e.
8.0/(-7.0)
, the result is roughly-1.143
.Your result using integer division is being rounded down toward the more negative value of
-2
. (This is also known as "Floor division")This is why you will get the somewhat perplexing answers of:
Note: This is "fixed" in Python 3, where the result of
8/(-7)
would be-1.143
. So if you have no reason to be using Python 2, you should upgrade. ;)In Python 3, if you still want integer division, you can use the
//
operator. This will give you the same answer as8/(-7)
would in Python 2.Here's a Python Enhancement Proposal on the subject: PEP 238 -- Changing the Division Operator
Python 总是对负数除法和正数除法进行“下限除法”。
那是
但有时我们需要 1/-10 为 0
我发现可以通过先使用 float 除法然后将结果转换为 int 来完成,例如
这对我来说效果很好,不需要导入未来的除法或升级到 Python 3
希望可以帮到你~
Python always does the "floor division" for both negative numbers division and positive numbers division.
That is
But sometime we need 1/-10 to be 0
I figure out it can be done by using the float division first then cast result to int, e.g.
That works fine for me, no need to import the future division or upgrade to Python 3
Hope it can help you~
要让 Python 自动将整数除法转换为浮点数,您可以使用:
现在:
此功能不在标准 Python 中 2 不要破坏依赖整数除法的现有代码。
但是,这是 Python 3 的默认行为。
To have Python automatically convert integer division to float, you can use:
Now:
This feature is not in the standard Python 2 not to break existing code that relied on integer division.
However, this is the default behavior for Python 3.
当除法时两个值都是整数时,Python 使用 Floor 除法。
When both values are integers when dividing Python uses Floor division.
在Python中,
/
运算符用于整数除法。您可以将其视为浮点数除法,然后进行向下取整运算。例如,
In Python,
/
operator is for integer division. You can look at it as float division followed by afloor
operation.For example,