递归函数来计算总和? [英] Recursive function to calculate sum?
本文介绍了递归函数来计算总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我所拥有的,但我不确定为什么它不起作用
This is what I've got and I'm not sure why it's not working
def sum(n):
if (n>0):
print (n)
return sum(n)+sum(n-1)
else:
print("done doodly")
number = int(input(": "))
sum(number)
例如如果使用输入5,我想编程计算5+4+3+2+1的总和.我做错了什么?
For example if the use inputs 5, I want to program to calculate the sum of 5+4+3+2+1. What am I doing wrong ?
推荐答案
两件事:
- 在为
n
计算sum
时调用sum(n)
不会对你有多大好处,因为你会无限递归.所以行return sum(n)+sum(n-1)
是不正确的;它需要是n
加上n - 1
其他值的总和.这也很有意义,因为这就是您想要计算的内容. - 您需要为基本情况和递归情况返回一个值.
- Calling
sum(n)
when computingsum
forn
won't do you much good because you'll recurse indefinitely. So the linereturn sum(n)+sum(n-1)
is incorrect; it needs to ben
plus the sum of then - 1
other values. This also makes sense as that's what you want to compute. - You need to return a value for the base case and for the recursive case.
因此,您可以将代码简化为:
As such you can simplify your code to:
def sum(n):
if n == 0:
return 0
return n + sum(n - 1)
这篇关于递归函数来计算总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文