英文:
Need help in understanding recursion function calls
问题
public class Main {
public static void main(String[] args) {
int test = 3;
printFun(test);
}
static void printFun(int test) {
if (test < 1) {
return;
} else {
System.out.printf("%d ", test);
// recursive call
printFun(test - 1);
System.out.printf("%d ", test);
return;
}
}
}
输出如下所示:
3 2 1 1 2 3
我可以帮助你理解为什么会出现这样的输出。根据你提供的代码,当printFun
函数递归调用时,会首先打印当前的test
值,然后递归调用printFun(test - 1)
,接着再次打印当前的test
值。这就是为什么输出中会出现额外的数字。递归是在函数调用自身的情况下发生的,所以在不同层次的递归中,会打印不同的数字。
如果你有关于这段代码或输出的更多疑问,请随时问我。
英文:
public class Main {
public static void main(String[] args) {
int test = 3;
printFun(test);
}
static void printFun(int test) {
if (test < 1) {
return;
} else {
System.out.printf("%d ", test);
// recursive call
printFun(test - 1);
System.out.printf("%d ", test);
return;
}
}
}
The output is coming as below
> 3 2 1 1 2 3
May anyone help me to understand how this output is coming.
As per my understanding, only 3 2 1 should print, please help me to understand for extra 1 2 3 in the output.
答案1
得分: 0
你在调用递归方法之前和之后都打印了这个值两次。移除第二个System.out.printf("%d ", test);
,然后应该就可以了。
英文:
You are printing the value twice, before calling the recursive method and afterwards.
Remove the second System.out.printf("%d ", test);
and it should be fine.
答案2
得分: 0
printFun() 函数之后的打印语句将在每次执行时被推送到堆栈中。因此,当循环结束时,所有的打印语句都会以相反的顺序执行。为了使输出为 3 2 1,您应该移除 printFun() 方法之后的打印语句。
英文:
The print statement after the printFun() function will be pushed to a stack each time. So, when the loop is finished all the print statements will execute in reverse order. To make the output as 3 2 1, you should remove the print statement after the printFun() method.
答案3
得分: 0
请查看以下针对输入3的函数调用:
printFun(3)-> { 打印3,调用printFun(2),打印3,返回 }
printFun(2)-> { 打印2,调用printFun(1),打印2,返回 }
printFun(1)-> { 打印1,调用printFun(0),打印1,返回 }
printFun(0)-> { 返回 }
想象一下,最初的调用将通过递归调用从上到下进行,然后从下到上返回。因此,它将打印3、2、1,然后是1、2、3。
英文:
Please find below function calls for input 3:
printFun(3)-> { print 3, call printFun(2) , print 3, return }
printFun(2)-> { print 2, call printFun(1) , print 2, return }
printFun(1)-> { print 1, call printFun(0) , print 1, return }
printFun(0)-> { return }
Imagine, initially calls will go up to down by recursive calls then down to up to return back. So, it will print 3,2,1 then 1,2,3
专注分享java语言的经验与见解,让所有开发者获益!
评论