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

/*程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21.... 从第3项开始为前2项之和*/

import java.util.Scanner;

public class RabitNum {
public static void main(String[] args) {
System.out.println("请输入月份");
Scanner scan = new Scanner(System.in);
int month = scan.nextInt();
int num = f(month);
System.out.println("兔子数为:"+num);
scan.close();
}
public static int f(int i) {
//前2个月为1
if(i==1 || i==2) {
return 1;
}
return f(i-1)+f(i-2);
}
}

猜你喜欢

转载自www.cnblogs.com/squirrel-xie/p/11067794.html