字符串形式浮点数转换为浮点数输出
时间: 2024-01-03 12:03:31 浏览: 89
以下是两种将字符串形式浮点数转换为浮点数输出的方法:
1.利用map和reduce编写一个str2float函数
```python
from functools import reduce
def str2float(s):
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def fn(x, y):
return x * 10 + y
n = s.index('.')
s1 = list(map(char2num, s[:n]))
s2 = list(map(char2num, s[n+1:]))
return reduce(fn, s1) + reduce(fn, s2) / 10 ** len(s2)
print(str2float('123.456')) # 输出:123.456
```
2.写一个转换函数,该函数的输入是一个表示浮点数的字符串,把该字符串转换成浮点数并输出
```python
def str_to_float(s):
flag = 1
if s[0] == '-':
flag = -1
s = s[1:]
if '.' not in s:
return flag * int(s)
else:
s1, s2 = s.split('.')
n1 = 0
for i in range(len(s1)):
n1 = n1 * 10 + ord(s1[i]) - ord('0')
n2 = 0
for i in range(len(s2)):
n2 = n2 * 10 + ord(s2[i]) - ord('0')
return flag * (n1 + n2 / 10 ** len(s2))
print(str_to_float('123.456')) # 输出:123.456
```
阅读全文
相关推荐
















