# 循环计算阶乘函数 0,1,2,3,4,5,6,7,8,9,10! 令人惊讶的是,6个星期的秒数居然也等于10! 不使用函数递归,实现一个阶乘计算函数(n<=170): ```python def fact(n): r = 1 # TODO(You): 请在此编写代码 return r if __name__ == '__main__': print(fact(10)) ``` 请选出下面的 Python 非递归阶乘实现代码中,错误 的选项。 ## template ```python def fact1(n): r = 1 for i in range(0, n): r *= (i+1) return r def fact2(n): r = 1 while (n > 0): r *= n n -= 1 return r def fact3(op): import math z = op + 1 p = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6] d1 = math.sqrt(2 * math.pi) / z i = 1 d2 = p[0] while i <= 6: d2 += p[i] / (z + i) i += 1 d3d4 = math.pow((z + 5.5), (z + 0.5))*math.exp(-(z + 5.5)) d = d1 * d2 * d3d4 return int(d) def fact4(n): import math r = math.factorial(n) return r if __name__ == '__main__': print(fact1(10)) print(fact2(24)) print(fact3(24)) print(fact4(10)) ``` ## 答案 ```python import math z = n + 1 p = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6] d1 = math.sqrt(2 * math.pi) / z i = 1 d2 = p[0] while i <= 6: d2 += p[i] / (z + i) i += 1 d3d4 = math.pow((z + 5.5), (z + 0.5))*math.exp(-(z + 5.5)) d = d1 * d2 * d3d4 r = int(d) ``` ## 选项 ### A ```python for i in range(0, n): r *= (i+1) ``` ### B ```python while n > 0: r *= n n -= 1 ``` ### C ```python import math r = math.factorial(n) ```