天天看点

斐波那契数列--Java不死神兔

案例:不死神兔

​ 有一对兔子,从出生后第3个月起每个月都生对兔子,

​ 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,

​ 问n月的兔子总数为多少?

​ 找规律:当月兔子个数 = 上月兔子个数+上上月兔子个数

​ 找出口:第一个月和第二个月兔子都是1对

import java.util.Scanner;
public class Test01 {
    /**
     * 不死神兔,兔子都不死,第8个月的兔子数量
     * 第N个月共会有多少对兔子
     */
    public static void main(String[] args) {
        final Scanner scan = new Scanner(System.in);
        System.out.print("请输入你想查询的第几个月后有多少对兔子:");
        int n=scan.nextInt();
        System.out.println("第"+n+"个月后有"+Rabbit(n)+"对兔子");
    }
    private static int Rabbit(int month){
        if (month==1||month==2){
            return 1;
        }
        else {
            return Rabbit(month-1)+Rabbit(month-2);
        }
    }
}