这个问题已经提过了。我已经为它编写了一个代码,但没有得到所需的输出。我们不需要求和,只需要显示所有的加数,这就是我遇到的问题
以下是我编写的代码:
x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for j in range(1,n+1):
factorial = factorial*j
for i in range(x,n+1):
s = (x**i)/factorial
print(s,end='+')
我的成果如下:
Please enter the base number: 2
Please enter the number of terms: 5
4.0+8.0+16.0+32.0+2.0+4.0+8.0+16.0+0.6666666666666666+1.3333333333333333+2.6666666666666665+5.333333333333333+0.16666666666666666+0.3333333333333333+0.6666666666666666+1.3333333333333333+0.03333333333333333+0.06666666666666667+0.13333333333333333+0.26666666666666666+
这显然不是我想要的答案。我想要的输出是这样的:
Please enter the base number: 2
Please enter the number of terms: 5
2.0+2.0+1.33333+0.66667+0.26667+
我应该在代码中进行哪些更改以获得所需的结果
你只需要一个循环。第二,试着从上一项计算下一项,以避免计算变得太大:
你不需要两个循环。您只需要一个循环,因为您的序列被泛化为
x**n/factorial(n)
,并且您只想增加n
的值这张照片是:
当然,如果要将数字格式化为固定的小数位数,请使用f字符串指定:
您的错误在第6行:
factorial = factorial*j
。 您应该做的是用factorial += 1
替换它,它将在每次您在循环中传递时按1递增阶乘这应该是正确的代码:
这就是结果:
如果有什么问题,请告诉我
相关问题 更多 >
编程相关推荐