如何修复“ 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3) 不等于 3.852 ”?

原文标题How to fix ” 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3) do not equal 3.852 “?

我有 number_list [‘3’, ‘.’, ‘8’, ‘5’, ‘2’] 并尝试通过转换回 3.852

>>> 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3)
3.8519999999999994

为什么我得到 3.8519999999999994,而不是 3.852 ?如何解决?部分计算独立工作。

>>> 3*10**(0)
3
>>> 8*10**(-1)
0.8
>>> 5*10**(-2)
0.05
>>> 2*10**(-3)
0.002

原文链接:https://stackoverflow.com//questions/71477020/how-to-fix-3100-810-1-510-2-210-3-do-not-equal-3-852

回复

我来回复
  • Tanvir Ahmed的头像
    Tanvir Ahmed 评论

    如果您想要 3 个小数点内的结果,您可以使用 python 内置函数round

    expression = 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3)
    round(expression, 3)
    
    2年前 0条评论