Skip to main content
 首页 » 编程设计

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

2025年05月04日15zengkefu

我用 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 

这只是一个显示问题,因为 float 的 str 和 repr 形式不同:

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