簡體   English   中英

使用python僅使用for和while循環對序列的n個項求和

[英]Using python to sum n terms of a sequence using only for and while loops

我不得不要求用戶輸入n個詞項,以及他們為該序列選擇的x值。

x^5/5 - x^7/7 + x^9/9 - x^11/11 + ...

我在每隔兩個字詞就說明符號更改時遇到了麻煩,並且不能使用任何if語句。

任何幫助將不勝感激,謝謝!

到目前為止,我的代碼:

print(" ")
print("Please enter the number of terms you would like to sum up.")
print("The sequence is x^5/5-x^7/7+x^9/9-...")
print(" ")
n=int(input('Number = '))
print(" ")
print("Please enter the number for x.")
print(" ")
x=int(input('x = '))
#
nsum=0
for i in range(5,n+6,2):
    coefficient=1/i
    for j in range(5,i+1,2):
        coefficient=-1*coefficient
    nsum=nsum+coefficient*x**i
#
print(nsum)

您的序列顯示,如果n為奇數,則第n個項為正,如果為偶數,則為負。 因此,您可以在for循環中執行此操作。 同樣在您的代碼中,用戶輸入n不等於項數:

nsum=0
for index in range(0, n):
    coefficient=(-1)**(index)
    i =  2*index + 5
    nsum=nsum+coefficient*x**i/i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM