如何使用forloop对前n个整数分数求和

2024-04-25 04:51:07 发布

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

如何创建使用for循环对前n个循环求和的程序 整数分数1/2+2/3+3/4+。。。。(n-1)/n+n/(n+1)。(n>;0为正 整数,总和中的最后一个数字是n/(n+1)

我试了很多次,但似乎都不管用


2条回答
n = int(input("Enter the nth term"))

fsum = 0
#Recommended to not use 'sum' itself 
#as it can cause problems with python's built in function which also has the same name

for i in range(1, n+1):
    fsum += i/(i+1)

print(fsum)  

我想这应该能解决你的问题

如果你想了解更多关于范围函数的信息,请参见 https://www.w3schools.com/python/ref_func_range.asp
注意,range函数只返回stop值,不包括stop值。在您的例子中stop值是变量n。这就是为什么我们必须在range函数中使用n+1

你可以试试

def sum_fraction(n):
    
    # Initialize the sum variable
    sum = 0
    
    # For loop : start from 1 ( n greater than zero ) : end with n
    for i in range(1, n):
        
        # Sum current term with all previous term (term by term)
        sum += i / (i + 1)
        
    return sum
        
n = 5
res = sum_fraction(n)

相关问题 更多 >