Python程序计算序列之和:1 + 1/2 + 1/3 +….. + 1 / N
问题描述
输入项数,并找到级数之和:1 + 1/2 + 1/3 +….. + 1/N
解决方案
1.输入项数以找到序列的总和。
2.将sum变量初始化为0。
3.使用范围从1到数字的for循环,找到序列的总和。
4.在四舍五入到小数点后两位后打印序列的总和。
5.退出。
程序/源代码
n=int(input("Enter the number of terms: ")) sum1=0 for i in range(1,n+1): sum1=sum1+(1/i) print("The sum of series is",round(sum1,2))
程序说明
1.用户必须输入项数才能找到总和。
2. sum变量初始化为0。
3. for循环用于查找级数之和,并且每次迭代均增加数字。
4.将数字添加到sum变量中,直到i的值达到项数为止。
5.然后打印系列的总和。
运行测试
Case 1: Enter the number of terms: 7 The sum of series is 2.59 Case 2: Enter the number of terms: 15 The sum of series is 3.32