Java-递归调用

A:递归概述: 方法定义中调用方法本身的现象
B:递归注意事项
要有出口,否则就是死递归
次数不能太多,否则就内存溢出
C:案例1:求整数n的阶乘
public class example {
public static void main(String[] args) {
Scanner scanner=new Scanner ( System.in );
System.out.println (“请输入一个正整数n:”);
int n=scanner.nextInt ();
int he=digui(n);
System.out.println (he);
}
public static int digui(int n){
if (n==1){
return 1;
}else{
return n*digui ( n-1 );
}
}
}
案例2:兔子问题(斐波那契数列)
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十个月的兔子对数为多少?
由此可见兔子对象的数据是:1 , 1 , 2 , 3 , 5 , 8 …
分析:从第三个数起,每个数等于前两个数之和。
public class example {
public static void main(String[] args) {
int r= duishu(20);
System.out.println®;
}

private static int duishu(int i) {
    //递归来做
    if(i==1||i==2){
        return 1;
    }else{
        return duishu(i-1)+duishu(i-2);
    }
}

}
答案是6765
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/PreyHard/article/details/82975712