本文介绍了请逐步解释递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请逐步解释递归;

public class TestClass {

    private static void printit(int i) {
        if (i == 1) {
            return;
        }
        System.out.println(i);
        printit(i / 2);
        printit(i / 2);
    }

    public static void main(String args[]) {
        int i = 8;
        printit(i);
    }
}


推荐答案

如果你正在使用IDE,你可以使用调试器,亲眼看看一步一步发生了什么。

If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.

无论如何,让我们尝试一下当我们调用递归时会发生什么方法:
你用8调用方法( printit(8); ):

Anyway, let's try and what happens when we call the recursive method:You call the method with 8 (printit(8);):


  1. System.out.println(8); - > 8

  2. printit(8 / 2); - >再次调用方法,8/2 = 4

  3. System.out.println(4); - > 4

  4. printit(4/2); >再次调用方法,4/2 = 2

  5. System.out.println(2); - > 2

  6. printit(2/2); >>再次拨打方法,2/2 = 1

  7. return; - >继续之前的通话,( printit(4/2);

  8. printit(2/2); >>再次调用方法,2/2 = 1

  9. return; - >继续以前呼叫,( printit(4/2);

  10. 方法结束,继续前一次呼叫( printit(8/2);

  11. printit(4/2); >致电方法再次使用4/2 = 2

  12. System.out.println(2); - > 2

  13. 调用 printit(2/2); 我们已经知道什么都没有。

  14. 现在我们在再次打电话, printit(8); ,要求 printit(8/2);

  15. System.out.println(4); - > 4

  16. 16等...

  1. System.out.println(8); -> 8
  2. printit(8 /2 ); -> Call to method again with 8/2=4
  3. System.out.println(4); -> 4
  4. printit(4 /2 ); > Call to method again with 4/2=2
  5. System.out.println(2); -> 2
  6. printit(2 /2 ); > Call to method again with 2/2=1
  7. return; -> Continues with previous call, the (printit(4 /2);)
  8. printit(2 /2 ); > Call to method again with 2/2=1
  9. return; -> Continues with previous call, the (printit(4 /2);)
  10. method finishes, continues with the previous call (printit(8 /2);)
  11. printit(4 /2 ); > Call to method again with 4/2=2
  12. System.out.println(2); -> 2
  13. calls printit(2/2); which we already know result in nothing.
  14. Now we are in the first call again, the printit(8);, calling for printit(8/2);
  15. System.out.println(4); -> 4
  16. 16 etc...

这篇关于请逐步解释递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 12:41