1

这个问题已经提到过。我已经为它编写了一个代码,但我没有得到想要的输出。我们不必实际找到总和,只显示所有单独的加数,这就是我遇到问题的部分。

这是我写的代码:

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+

我应该在代码中进行哪些更改以获得所需的结果?

  • 旁注:我正在使用 Python 版本 3.8.5 的 Mac
4

3 回答 3

0

你只需要一个循环。其次,尝试从前一项计算下一项,以防止计算变得非常大:

value = 1
for j in range(1,n+1):
    value *= x / j
    print(value,end='+')
于 2021-05-03T15:27:30.293 回答
0

你不需要两个循环。您只需要一个循环,因为您的系列已推广到x**n/factorial(n)并且您只想增加n.

x = 2 # int(input("Please enter the base number: "))
n = 5 # int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,n+1):
    factorial = factorial*i
    s = (x**i) / factorial
    print(s, end='+')

这打印:

2.0+2.0+1.3333333333333333+0.6666666666666666+0.26666666666666666+

当然,如果要将数字格式化为固定的小数位数,请使用 f-string 指定:

for i in range(1,n+1):
    factorial = factorial*i
    s = (x**i) / factorial
    print(f"{s:.6f}", end='+')
2.000000+2.000000+1.333333+0.666667+0.266667+
于 2021-05-03T15:24:41.897 回答
-1

您的错误在第 6 行:factorial = factorial*j。您应该做的是替换它,factorial += 1每次通过循环时都会将阶乘加一。

这应该是更正的代码:

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+1
    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
2.0+4.0+8.0+16.0+1.3333333333333333+2.6666666666666665+5.333333333333333+10.666666666666666+1.0+2.0+4.0+8.0+0.8+1.6+3.2+6.4+0.6666666666666666+1.3333333333333333+2.6666666666666665+5.333333333333333+

让我知道是否有任何问题。

于 2021-05-03T15:33:36.737 回答