用循环结构计算式的和(显示小数点后6位)
变量×与n的数值由用户输入
>>> x, n = map(int, input('请输入x和n,以逗号分割:').split(','))
请输入x和n,以逗号分割:3,5
>>> s, f = 1+x, 1 # 结果和阶乘
>>> for i in range(n):
f *= i+2
s += pow(x, i+1)/f
>>> print('%.6f'%s)
9.137500
from math import factorial as fact
def func(x,n):
s = x
for i in range(n+1):
s += x**i/fact(i+1)
return round(s,6)
>>> func(0.5, 100)
1.797443
>>> func(1, 1000)
2.718282
# 当x为小数时,n值不能太大。超出浮点数最大值会报错:OverflowError: int too large to convert to float