我试图理解递归是如何工作的,我从简单的例子开始,我用简单的阶乘程序来理解它,但是当我添加超过一行代码时,很难理解它是如何工作的。
下面是我的代码:
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的重复感到困惑,为什么以及如何出现这种重复
发布于 2019-09-29 22:54:47
有时,在方法调用中放置信息字符串有助于跟踪正在发生的事情。你可以在你认为合适的时候调整它们,然后放入其他东西,比如间距和缩进。这只是给你一个想法。
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);
}发布于 2019-09-29 22:00:13
一旦调用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。
https://stackoverflow.com/questions/58155834
复制相似问题