sum=(1**2)+(2**2)(3**2)+(4**2),…,+(n**2)python程序代码

2024-04-16 23:58:06 发布

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

Write a program to show the sum of (1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2) program code in python using "for" and "While" loop.

虽然我只为如下代码所示的+迭代编写,但是+,-,+,-迭代非常困难。这是我的+迭代代码:

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)]

Tags: andofto代码inforshowcount
2条回答

您可以执行% 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

相关问题 更多 >