繁体   English   中英

编写 Python 程序以打印以下数字序列(N 由用户输入):X + X^3/3。 + X^5/5.... 直到第 N 项

[英]Write a Python program to print the following sequence of numbers (N to be entered by user): X + X^3/3! + X^5/5!... Upto the Nth Term

我在这个问题上遇到的问题是我编写的代码显示了一个逻辑错误。 这是我写的代码:

x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,n+1,2):
    factorial = factorial*i
    s = (x**i) / factorial
    #using f string to format the numbers to a fixed number of decimal places
    print(f"{s:.6f}", end='+')

我使用 for 循环仅显示索引的奇数值,因为这是问题中的要求。 我的 output 如下:

Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+

我们不必实际找到总和,只需显示用加号分隔的所有单个加数。 我应该在代码中进行哪些更改以获得所需的结果?

我需要的 output 看起来像这样:

Please enter the base number: 2
Please enter the number of terms: 4
2.000000+1.333333+0.266666+0.025396

只需更改为
for i in range(1,2*(n)+1,2):

for i in range(1,n+1,2):

现在,output 是:

Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+2.133333+1.219048+

此外,计算factorial的方法是错误的,因为当您将i从 1 跳到 3 到 5 时,它会跳过一半的项,因此会错过2, 4, 6..
所以,你可以这样做:

if i > 1:
    factorial = factorial*i*(i-1)
elif i == 1:
    factorial*i

因此,最终代码将是:

x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,2*n+1,2):
    if i > 1:
        factorial = factorial*i*(i-1)
    elif i == 1:
        factorial*i
    s = (x**i) / factorial
    #using f string to format the numbers to a fixed number of decimal places
    print(f"{s:.6f}", end='+')

阶乘在循环中,但循环执行 i=1,3,5 而不是 i=1,2,3,4,5,这可能是个问题。 如果“术语数”:“2.000000+2.666667”是两个,那么在循环中,您的范围 avec 直到 n*2 而不是 n 但要小心,因为工厂将被更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM