编写一个Python程序来打印以下数字序列(N由用户输入):X+X^2/2!+X^3/3!+。。。最多n项

2024-05-13 08:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题已经提过了。我已经为它编写了一个代码,但没有得到所需的输出。我们不需要求和,只需要显示所有的加数,这就是我遇到的问题

以下是我编写的代码:

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电脑上工作

Tags: ofthe代码innumberforinputbase
3条回答

你只需要一个循环。第二,试着从上一项计算下一项,以避免计算变得太大:

value = 1
for j in range(1,n+1):
    value *= x / j
    print(value,end='+')

你不需要两个循环。您只需要一个循环,因为您的序列被泛化为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字符串指定:

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+

您的错误在第6行:factorial = factorial*j。 您应该做的是用factorial += 1替换它,它将在每次您在循环中传递时按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+

如果有什么问题,请告诉我

相关问题 更多 >