负整数除法令人惊讶的结果

编程入门 行业动态 更新时间:2024-10-23 10:29:56
本文介绍了负整数除法令人惊讶的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

负整数除法令人惊讶的结果

本文发布于:2023-10-25 13:43:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   惊讶   整数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!