简单的递归示例-请帮助我理解递归 [英] simple recursive example - please help me understand recursion
问题描述
public static int triple(int n)
{
if (n == 0)
return 0;
else
total = 3 + triple(n-1);
System.out.println(total);
return total;
}
好吧,所以我有一个我似乎无法理解的简单的示例,我希望有人能够帮助我逐步了解程序如何获取输出.
Ok, so I've got this simple recusion example that I just cant seem to grasp, I was hoping someone would be kind enough to walk me through cycle by cycle of how the program gets its output.
这就是我认为会发生的事情.可以说n=5
因此,程序循环并命中total = 3 + triple(5-1)
我认为这等于7.这是错误的
程序打印
Here is what I thought would happen. Lets say n=5
So, the program cycles and hits total = 3 + triple(5-1)
which i would think would be equal to 7.. which is wrong
the program prints
3
6
9
12
15
3
6
9
12
15
所以...然后我认为三元组必须在打印总计之前再次运行...我相信确实如此,但我只是不明白那时的总计如何.
So... then I thought triple must run through again before printing the total... which I believe it does but I just don't understand how it comes to its totals at all then.
因为它看起来像这样:
3 + triple(4)
3 + triple(3)
3 + triple(2)
3 + triple(1)
=3
有人可以请你解释一下,因为我很迷茫!
Can someone explain please, as you can I am very lost!
推荐答案
您在解释它时略有错误.像这样:
You're interpreting it slightly wrong. It's more like this:
triple(5) = 3 + triple(4)
triple(4) = 3 + triple(3)
triple(3) = 3 + triple(2)
triple(2) = 3 + triple(1)
triple(1) = 3 + triple(0)
triple(0) = 0
现在想象triple(0)
,triple(1)
等都是单独的变量,并通过逐步解决来解决triple(5)
.
Now imagine that triple(0)
, triple(1)
, etc. are all individual variables, and solve for triple(5)
by working your way up.
这篇关于简单的递归示例-请帮助我理解递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!