等式:1 + 1/2!+ 1/3 !+ 1/4 !…+ 1/n !——比;(n & lt;10)
#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 Loop-------
s = 1
for x in range (2,10) :
s += (1/fact(x))
print(s)
#-----------------------------
如果总是n <10、那么为什么每次都要计算阶乘
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个数的阶乘,并执行上述操作。
可以使用math.fact
import math
s = 1
for x in range (2,10) :
s += (1/math.fact(x))
print(s)