gpt4 book ai didi

python除法结果与负数不同

转载 作者:行者123 更新时间:2023-11-28 21:21:52 32 4
gpt4 key购买 nike

在使用 python 命令行时,我注意到以下几点:

Python 2.7.3 |EPD_free 7.3-2 (64-bit)| (default, Apr 11 2012, 17:52:16)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "credits", "demo" or "enthought" for more information.
>>> 9/7
1
>>> -9/7
-2
>>>

有人可以指出为什么我的答案与负数除法不同吗?谢谢。

最佳答案

在 Python 2.X 中,/ 实际上是整数和长整数的底除法:

The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs. [source: PEP 238]

如果您想对整数/长整数使用真正的除法,您可以将 from __future__ import division 添加到您的模块(或切换到 3.X)。如果这样做,您可以通过执行 x//y 来使用楼层划分。

>>> 9/7
1
>>> -9/7
-2
>>> from __future__ import division
>>> 9/7
1.2857142857142858
>>> -9/7
-1.2857142857142858

关于python除法结果与负数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20570034/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com