def summ(n):
if n%2:
m=1
else:
m=2
return round(sum([1/x for x in range(m,n+1,2)]),2)
print(summ(5))
def sumlist(n):
if n%2==0:
numlist=[1/(2*x) for x in range(1,(n/2)+1)]
return round(sum(numlist),2)
else:
numlist=[1/x for x in range(1,(1/n)+1
reurun round(sum(numlist),2)
n=int(input())
sum=0
if n%2==1:
for i in range(2,n+1,2):
sum+=1/i
else:
for i in range(2,n+1,2):
sum+=1/i
print(round(sum,2))
比较常规的方法:
def test(n):
a=0
if n % 2 == 0:
for i in range(2,n+1,2):
a=a + (1/i)
else:
for i in range(1,n+1,2):
a=a +(1/i)
return a
效率更高一点的方法:
import numpy as np
def test_1():
n=input("请输入需要计算的自然数:")
n=float(n)
if n<=0 or n!=int(n):
print("请确保输入的数值是自然数(大于0的整数)")
elif n%2==0:
a=np.arange(2,n+1,2)
print("计算结果是:" + str(sum(1/a)))
else:
a=np.arange(1,n+1,2)
print("计算结果是:" + str(sum(1/a)))