需要帮助理解递归函数调用。

huangapple 未分类评论55阅读模式
英文:

Need help in understanding recursion function calls

问题

  1. public class Main {
  2. public static void main(String[] args) {
  3. int test = 3;
  4. printFun(test);
  5. }
  6. static void printFun(int test) {
  7. if (test < 1) {
  8. return;
  9. } else {
  10. System.out.printf("%d ", test);
  11. // recursive call
  12. printFun(test - 1);
  13. System.out.printf("%d ", test);
  14. return;
  15. }
  16. }
  17. }

输出如下所示:

  1. 3 2 1 1 2 3

我可以帮助你理解为什么会出现这样的输出。根据你提供的代码,当printFun函数递归调用时,会首先打印当前的test值,然后递归调用printFun(test - 1),接着再次打印当前的test值。这就是为什么输出中会出现额外的数字。递归是在函数调用自身的情况下发生的,所以在不同层次的递归中,会打印不同的数字。

如果你有关于这段代码或输出的更多疑问,请随时问我。

英文:
  1. public class Main {
  2. public static void main(String[] args) {
  3. int test = 3;
  4. printFun(test);
  5. }
  6. static void printFun(int test) {
  7. if (test &lt; 1) {
  8. return;
  9. } else {
  10. System.out.printf(&quot;%d &quot;, test);
  11. // recursive call
  12. printFun(test - 1);
  13. System.out.printf(&quot;%d &quot;, test);
  14. return;
  15. }
  16. }
  17. }

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(&quot;%d &quot;, 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的函数调用:

  1. printFun(3)-> { 打印3,调用printFun(2),打印3,返回 }
  2. printFun(2)-> { 打印2,调用printFun(1),打印2,返回 }
  3. printFun(1)-> { 打印1,调用printFun(0),打印1,返回 }
  4. printFun(0)-> { 返回 }

想象一下,最初的调用将通过递归调用从上到下进行,然后从下到上返回。因此,它将打印3、2、1,然后是1、2、3。

英文:

Please find below function calls for input 3:

  1. printFun(3)-&gt; { print 3, call printFun(2) , print 3, return }
  2. printFun(2)-&gt; { print 2, call printFun(1) , print 2, return }
  3. printFun(1)-&gt; { print 1, call printFun(0) , print 1, return }
  4. printFun(0)-&gt; { 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

huangapple
  • 本文由 发表于 2020年5月4日 18:26:43
  • 转载请务必保留本文链接:https://java.coder-hub.com/61590065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定