gpt4 book ai didi

python - Python int() 的转换问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:57 26 4
gpt4 key购买 nike

当我运行此代码时:

value = 11.20
dollars = int(value)
print dollars
print 100 * (value - dollars)

不出所料,我分别得到了 1120.0

但是,当添加此行时:

print int(100 * (value - dollars))

我得到了19

我在网上搜索了一下,得到了解释:

But 0.20 is different. Inside the computer, it's actually a slightly smaller number, so multiplying by 100 gives 19.99999.... When int cuts off the part after the decimal point, 19 is left as the result, instead of the expected 20.

然后我尝试了:

value_tmp = 0.20
print int(value_tmp * 100)

我得到20,而不是19,这里有什么问题吗?

最佳答案

您的近似值为 20.0:

>>> value = 11.20
>>> dollars = int(value)
>>> 100 * (value - dollars)
19.99999999999993

这是因为您无法使用 float 准确地建模 2/10:

>>> value
11.2
>>> format(value, '.53f')
'11.19999999999999928945726423989981412887573242187500000'

通过将小数部分乘以 100,您放大了这种不精确性。将结果添加到float数字上的int()下限结果。

您可以将数字四舍五入为最接近的整数:

>>> round(100 * (value - dollars), 0)
20.0
>>> int(round(100 * (value - dollars), 0))
20

关于python - Python int() 的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026110/

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