在我的应用程序中,我遇到以下问题,并对结果感到惊讶:
In my application I encountered the following and was surprised by the results:
8 / -7 = -2 (两个整数)。
这是什么意思?
推荐答案对于实际值,即 8.0 /(-7.0),结果大约为 -1.143 。
For the actual values, i.e. 8.0/(-7.0), the result is roughly -1.143.
使用整数除法得到的结果将向下舍入为 -2 的负值。 (这也称为楼层划分)
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:
>>> 8/(-7) -2 >>> 8/7 1注意:已修复在Python 3中,其中 8 /(-7)的结果将为 -1.143 。因此,如果您没有理由使用Python 2,则应该升级。 ;)
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. ;)
在Python 3中,如果仍然需要整数除法,则可以使用 // 运算符。这将为您提供与 8 /(-7)在Python 2中相同的答案。
In Python 3, if you still want integer division, you can use the // operator. This will give you the same answer as 8/(-7) would in Python 2.
这里是Python关于此主题的增强建议: PEP 238-更改除法运算符
Here's a Python Enhancement Proposal on the subject: PEP 238 -- Changing the Division Operator
更多推荐
负整数除法令人惊讶的结果
发布评论