Python计算1.0的float类型使用int()转换为零

时间:2016-04-29 02:23:34

标签: python

我是python的新手,所以我希望我在这里缺少一些类型的基本知识。我正在尝试创建一个字符串,其中我采用浮点数并用字符串替换小数点。在这样做时,我尝试调用一行代码相当于:

int(pow(10, 1)*(5.1%1)))

但是如果你运行这段代码:

x = pow(10, 1)*(5.1%1)
print(x)
print(type(x))
print(int(x))
print(int(1.0))
print(type(1.0))

它返回:

1.0
<type 'float'>
0
1
<type 'float'>

我认为这里存在类型问题,但它们都是float类型。那么为什么int(x)返回零而不是int(1.0)?

1 个答案:

答案 0 :(得分:2)

由于舍入误差,你没有得到1,但没有得到

>>> x = pow(10, 1)*(5.1%1)
>>> print '{:.20f}'.format(x)
0.99999999999999644729

当你展示它时,你正在为你收集一些其他的东西

>>> x = pow(10, 1)*(5.1%1)
>>> print x
1.0
>>> print '{:.10f}'.format(x)
1.0000000000

为了获得显示的内容肯定会提供相同的数字(稍微好一点的调试),使用repr出于习惯

>>> x = pow(10, 1)*(5.1%1)
>>> print repr(x)
0.9999999999999964
>>> print 'hello {!r} world'.format(x)
hello 0.9999999999999964 world