文章目录
递归
概述
方法定义调用方法本身
注意事项
需要有一个临界值 否则就是一个死循环
阶乘
package org;
public class Test {
public static void main(String[] args) {
//求5的阶乘
System.out.println("5的阶乘=" + num(5));
}
public static int num(int a){
if(a == 1){
return 1;
}else {
return a * num(a-1);
}
}
}
/*
5的阶乘=120
*/
兔子问题(斐波那契数列)
package org;
public class Test {
public static void main(String[] args) {
//有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,
//假如兔子都不死,问第二十个月的兔子对数为多少?
//由此可见兔子对象的数据是:1 , 1 , 2 , 3 , 5 , 8 ...
//前两个数之和等于下一个数
System.out.println("兔子对数=" + num(20));
}
public static int num(int month){
if (month == 1 || month == 2){
return 1;
}else {
return num(month-1)+num(month-2);
}
}
}
/*
兔子对数=6765
*/