Discuss / Python / 作业第三题 小数点那里查阅了一下别人的博客 但是还是不是很明白为什么会出错 求讲解

作业第三题 小数点那里查阅了一下别人的博客 但是还是不是很明白为什么会出错 求讲解

Topic source

Fwmmmm-

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reducedef str2float(s):    n = len(s) - (s.index('.')) - 1   # n为小数点右边的的小数位数,写成n = s.index('.')会出现小数点位置错误    L1 = reduce(lambda x,y:x*10+y, map(int, s.replace('.', '')))    return L1 / (10 ** n)print(str2float('123.456'))

Fwmmmm-

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

但是我试了一下没有问题啊

from functools import reducedef str2float(s):    n=s.index('.')    L1 = reduce(lambda x,y:x*10+y, map(int, s.replace('.', '')))    return L1 / (10 ** n)print('str2float(\'123.456\') =', str2float('123.456'))if abs(str2float('123.456') - 123.456) < 0.00001:    print('测试成功!')else:    print('测试失败!')

  • 1

Reply