古典兔子问题

package com.mumu.ready;

import java.util.Scanner;

public class Rabbit {
//题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
// 1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
public static void main(String[] args) {
Scanner can =new Scanner(System.in);
System.out.println("请输入月份:");
int month=can.nextInt();
while(month<1){//这里若是if判断则只会判断一次,不会判断再一次的输入
System.out.println("请输入正确的月份:");//正确月份是指大于0的正整数
month=can.nextInt();
}
System.out.println("这个月的兔子总数是:"+f(month));
}
public static int f(int m) {
if(m<3) return 1;
else return f(m-1)+f(m-2);
}
}

原文地址:https://www.cnblogs.com/liumumu2014/p/3822405.html