有一对兔子,从出生后第3个月起每个月都生一对兔子, 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死, 问每个月的兔子总数为多少?

古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,
小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
问每个月的兔子总数为多少?

程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....

public class 第一题兔子问题 {
public static void main(String[] args) {
    System.out.print("请输入月份:");
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int total = 0; //记录耗子总数
    int y = 2; //记录老耗子
    int x1 = 0; //记录满一个月的耗子
    int x2 = 0; //记录满两个月的耗子
    int x3 = 0;  //记录满三个月的耗子
    for(int i=0; i<n; i++) {
        y += x3; //新的老耗子数量 = 老耗子 + 满三个月的耗子
        x3 = x2;
        x2 = x1;
        x1 = y;
    }
    total = y + x1 + x2 + x3;
    System.out.println(n + "个月后的耗子数量为" + total + "只");
    in.close();
}
}

猜你喜欢

转载自www.cnblogs.com/zjulanjian/p/10952768.html