Discuss / Python / 参考各位答案写出来的

参考各位答案写出来的

Topic source

nstart0902

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

# -*- coding: utf-8 -*-

from functools import reduce

digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2float(s):

    n=s.index('.') #找出.的位置

    t=len(s)

    p=t-n-1     #结果需要乘10的-p次幂

    s=s.replace('.','') #去掉字符串中的. 用空字符串替换

    def char2num(x):

        return digits[x]

    sf=reduce(lambda x,y:x*10+y,map(char2num,s))

    return sf*pow(10,-p)

print('str2float(\'123.456\') =', str2float('123.456'))

#if abs(str2float('123.456') - 123.456) < 0.00001:

if abs(str2float('123.456') - 123.456) == 0:

    print('测试成功!')

else:

    print('测试失败!')


  • 1

Reply