簡體   English   中英

sum = (1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2) python 程序代碼

[英]sum = (1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2) program code in python

編寫一個程序來顯示(1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2)的總和程序代碼在 python 中使用“for”和“While”循環。

雖然我在代碼中只寫了如下所示的+迭代但是+,-,+,-迭代非常困難。 這是我的+迭代代碼:

nstart = 1
nend = 4
count = 0
Sum = 0
for i in range(nstart,nend+1):
    count+=1
    d = i**2
    Sum = Sum + d
    print(count,'**2 = ', d )

print('Sum = ', Sum)
#This program print same as [(1**2,+ 2**2,+ 3**2= 9,+,,,,+n**2 and sum of them)]

您可以執行% 2檢查以檢查奇數並將符號設置為+-相應地:

sum = 0
for i in range(1, n+1):
    if i != 1 and i % 2:
        sum -= (i ** 2)
    else:
        sum += (i ** 2)

對於n值 4,這將輸出 12。

另一種選擇:使用sign變量並相應地更改它。

sum = 1**2
sign = 1 #positive
for i in range(2, n+1):
    sum += sign * (i ** 2)
    sign *= -1 #flip sign

暫無
暫無

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

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