问题描述
n = 10
10+9+8+7+6+5+4+3+2+1 = 55
这是一段代码,用于将数字从 n 开始添加到它之前的每个数字.
here's a piece of code to add number starting from n, to every number before it.
public static int recursion(int index){
if (index == 0){
return 0;
}
else{
return recursion(index-1) + index;
}
}
抱歉问了一个愚蠢的问题,但让我感到困惑的是:当索引不为零时,它再次调用递归函数,将索引减去 1,依此类推,直到索引为零.但是,它是编码递归(index-1) + index.
sorry for stupid question, but here's what confuse me: when the index is not zero, it calls the recursion function again, with the index substracted by 1, so on until the index is zero. However, it's coded recursion(index-1) + index.
那么为什么每次调用该函数时索引不减去1并加上10(或任何索引号)?为什么不是这样的:(10+ (9+10) + (8+10) + (7+10) +....) ?
so why the index is not substracted by 1 and added by 10 (or any index number) each time the function is called? why is it not something like this: (10+ (9+10) + (8+10) + (7+10) +....) ?
推荐答案
试着把这个总和写成
sum(10) = 1+2+3+4+5+6+7+8+9+10
这会让你看到
sum(10) = (1+2+3+4+5+6+7+8+9)+10 = sum(9)+10
和
sum(9) = (1+2+3+4+5+6+7+8)+9
等等
换句话说
sum(i) = sum(i-1) + i;
或者更准确地说
{0 for i=0
sum(i) = {
{sum(i-1) + i for i>0
顺便说一句,每次调用方法时,它的变量在每个方法调用中都是单独的实例,这意味着 recursion(10)
中的 index
是与 indexrecursion(9)
中的code>.
BTW each time method is called its variables are separate instances in each method call which means index
in recursion(10)
is separate variable than index
in recursion(9)
.
这篇关于需要帮助来理解递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!