写了个输入计算精度,求e近似值的算法,请问下为什么会在第八行报错,及如何修改
原算法:
def factorial(a):
if a == 1:
return a
else:
return (a * factorial(a - 1))
b = 1
c = 1
while b <= int(input()):
c = c + 1 / factorial(b)
b = b + 1
print(c)
报错结果:
line 8, in
while b <= int(input()):
ValueError: invalid literal for int() with base 10: ''
def fac(x):
if x == 1 or x == 0:
return x
else:
return x * fac(x - 1)
i = 1
s = 1
a = eval(input()) #精度
while 1 / fac(i) >= a:
s = s + 1 / fac(i)
i += 1
s = s + 1 / fac(i)
print(s)
代码没错,但是不合理。
应该是输入错了,不能转为数字。
input放到while里,不太合理。每循环输入一次,没道理