gpt4 book ai didi

python - 为什么 is_integer() 方法不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:08 28 4
gpt4 key购买 nike

我用 Python 写了这段代码:

x=345**3
z=float(x)**(1.0/3.0)
print z
print z.is_integer()

输出是:

345.0
False

这是为什么呢?我希望输出为 True

最佳答案

因为 z 不完全是 345.0:

>>> x = 345 ** 3
>>> z = float(x) ** (1.0 / 3.0)
>>> print z
345.0
>>> (345.0).is_integer()
True

到目前为止一切都很好,但是:

>>> z.is_integer()
False
>>> z == 345.0
False
>>> z
344.9999999999999

这只是一个显示问题,因为 floatstrrepr 形式不同:

>>> z.__repr__()
'344.9999999999999'
>>> z.__str__()
'345.0'

关于python - 为什么 is_integer() 方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201816/

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