简体   繁体   English

我想根据用户输入 N 使用递归 function 计算前 N 个偶数的总和

[英]I want to compute the sum of first N even numbers based on the user input N using recursive function

I want to compute the sum of first N even numbers based on the user input N using recursive function.我想使用递归 function 根据用户输入 N 计算前 N 个偶数的总和。

For example:例如:

Sample Input N: 5样本输入 N:5

Sample Output: 2 + 4 + 6 + 8 + 10 = 30样品 Output:2 + 4 + 6 + 8 + 10 = 30

I did my code in 2 ways but both of them gave wrong outputs.我以两种方式编写代码,但它们都给出了错误的输出。 I'm doing something wrong in the function part sorting number in the loop.我在循环中的 function 零件排序号中做错了。 So I need some help!所以我需要一些帮助!

n = int(input("Enter a nmuber: "))
for i in range(1,n+1):
   for d in range(0,i+1,2):
       print(d)
   
n = int(input("Enter a number: "))
def get_even(n):
    for i in range(1,n+1,2):
        d += i
        print(d)

You can use the following.您可以使用以下内容。

Code代码

def sum_even(n):
    # Base case
    if n <= 1:
        return 0
    
    if n % 2:
        # odd n
        return sum_even(n - 1)     # sum from next smaller even
    else:
        # even n
        return n + sum_even(n - 2) # current plus sum from next smaller even

# Usage
n = int(input('Enter a nmuber: '))
print(sum_even(n)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个函数 function(n) 接受一个整数,并使用 while 循环返回前 n 个偶数的总和? - How do I write a function function(n) that takes in an integer, and returns the sum of the first n even numbers using a while loop? 编写一个 function (递归),它将计算从 1 到 n 的偶数之和 - write a function (recursive) that will calculate the sum of even numbers from 1 to n N个数字的输入中的偶数和 - Sum Of even numbers among the input of N numbers 计算前“n”个自然数的立方和与前“n”个自然数的平方和的比率 - Compute the ratio of the sum of cube of the first 'n' natural numbers to the sum of square of first 'n' natural numbers 创建一个带有递归函数的 Python 脚本来显示前 n 个整数的总和,其中 n 由用户输入 - creating a Python script with a recursive function to display the sum of the first n integers, where n is entered by the user 如何使用递归 function 计算和打印以下序列的前 N 个元素的总和 - How can i calculate and print the sum of first N elements of below sequence using recursive function 如何使用for循环编写一个迭代函数来计算前n个奇数的和,它返回1 + 3 +…+(2n-1)? - How do I write an iterative function that computes the sum of the first n odd numbers it returns 1 + 3 + … + (2n - 1), using a for loop? 使用 n 输入在 python 中递归 function - Recursive function in python using n input P(n) 和递归 function - Sum of P(n) with a recursive function 前 n 个斐波那契数的和 - Sum of the first n fibonacci numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM