负整数除法令人惊讶的结果 [英] Negative integer division surprising result

查看:107
本文介绍了负整数除法令人惊讶的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我遇到以下问题,并对结果感到惊讶:

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

这篇关于负整数除法令人惊讶的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆