我试图了解递归的工作原理,我以一个简单的示例开始,以简单的阶乘程序来理解它,但是当我添加多行代码时,很难理解其工作原理。
下面是我的代码:
public class ProceduralProgramming {
public static void main(String[] args)
{
fact(3);
}
public static void fact(int n)
{
if (n>=1)
{
fact(n-1);
fact2(n);
fact(n-1);
}
}
public static void fact2(int n)
{
System.out.println(n);
}
}
我得到以下输出:
1
2
1
3
1
2
1
我对1
的重复感到困惑,为什么会这样重复以及如何重复
答案 0 :(得分:0)
一旦调用fact(n-1)
,您将跳回到fact()
函数的顶部,并且fact()
的当前迭代位于“堆栈”中;等待下一次迭代完成:
fact(3-1) calls fact(2) which calls fact(1) which calls fact(0)
fact(1) -> continues, prints 1 and calls fact(0)
fact(2) -> continues, prints 2, calls fact(1) which calls fact(0)
fact(1) -> continues, prints 1, calls fact(0)
etc...
一个很大的帮助是下载正确的IDE并学习使用调试器,该调试器使您可以逐行浏览程序并查看当前值。检出IntelliJ Community Edition。
答案 1 :(得分:0)
有时,在信息调用中添加信息性字符串有助于跟踪正在发生的事情。您可以根据需要调整这些值,并放入其他内容,例如间距和缩进。这只是为了给您一个想法。
public class ProceduralProgramming {
public static void main(String[] args) {
fact("Initial fact call : ", 3);
}
public static void fact(String note, int n) {
System.out.println("Entered Fact - " + note + n);
if (n >= 1) {
fact("First fact call : ", n - 1);
System.out.println("returned from first fact call");
fact2("Fact2 call : ", n);
System.out.println("returned from fact2 call");
fact("Second fact call : ", n - 1);
System.out.println("returned from second fact call");
}
}
public static void fact2(String note, int n) {
System.out.println(note + n);
}
}
从递归调用返回的第二个示例。
public static void doit(int n) {
if (n < 1) {
return;
}
System.out.println("Value of n before call: " + n);
doit(n-1);
// previous n's will be listed here in reverse order.
System.out.println("Value of n when returning: " + n);
}