用python计算1-3+5-7+…-99+101

用python计算1-3+5-7+…-99+101
算法实现如下:
第一种

i=1
j=0
while abs(i)<103:
    j+=i
    if i>0:
        i+=2
        i=-i
    else:
        i=-i
        i+=2
print(j)

第二种:
使用for循环:

s=0
for i in range(1,102,4):
	s+=i
t=0
for i in range(3,100,4):
	t+=i
print(s-t)

第三种:
使用while循环:

s=0
i=1
while i<=101:
    s+=i
    i+=4
t=0
y=-3
while y>=-99:
    t+=y
    y-=4
print(s+t)

你可能感兴趣的:(python,python)