Discuss / Python / 第三题结果为什么会有很多位小数

第三题结果为什么会有很多位小数

Topic source

nishno_s45

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce
def str2num(x):
    dicts={'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0,'.':-1}
    point=-2
    num=map(lambda x:dicts[x],x)
    def int2flo(f,n):
        nonlocal point
        if n==-1:
            point=1
            return f
        elif point==-2:
            return f*10+n
        else:
            point=point*10
            return f+n/point
    return reduce(int2flo,num)

print(str2num('123.123'))

结果是123.12299999999999

这是为什么呢

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

因为浮点数在计算机中无法精确表示,永远不可能精确存储无限循环小数

所以浮点数的==比较不可靠,浮点数输出为字符串要用格式化来指定小数位,例如:

print('%.2f' % f)

  • 1

Reply