递归
递归结构包括两部分:
-
递归头:什么时候不调用自身方法,如果没有头,将陷入死循环
-
递归体:什么时候需要调用自身方法
package com.cheng.method;
public class Demo04 {
// public static void main(String[] args) {
// Demo04 demo04 = new Demo04();
// demo04.test;
// }
// public void test()P{
// test();
// }
// 以上注释代码运行结果报错,栈溢出。
//test方法不加static则需在main方法
//Demo04 demo04 = new Demo04();
//demo04.test;
//结城
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
System.out.println(demo04.factorial(5));
}
public int factorial(int f){
if (f == 1){//如果为1返回1
return 1;
}else {//不唯一返回 f*(f-1)此处(f-1)调用factorial方法
return f*factorial(f-1);
}
}
//小计算可以递归,大的就免了
}