问题描述
方程:1 + 1/2! + 1/3! + 1/4! ... + 1/n! --> (n
#define factorial
def fact(x):
if x == 0:
return 1
else:
return x * fact(x-1)
#define factorial
def fact(x):
if x == 0:
return 1
else:
return x * fact(x-1)
#---------漫漫长路------------
#equation= 1 + 1/fact(2) + 1/fact(3) + 1/fact(4) + 1/fact(5) + 1/fact(6)+ 1/fact(7) +
#1/fact(8)+ 1/fact(9)
#print(equation)
#---------with for 循环-------
s = 1
for x in range (2,10) :
s += (1/fact(x))
print(s)
#-----------------------------
解决方法
一种方法是使用 math.fact
import math
s = 1
for x in range (2,10) :
s += (1/math.fact(x))
print(s)
,
如果它总是 n
s = 1
y = 9*8*7*6*5*4*3*2
j = 9
while j >1:
s += (1/y)
y = y/j
j = j-1
print(s)
或者只计算第 n 个数字的阶乘并执行与上述相同的操作。