题目:
古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?
程序分析:
兔子的规律为数列 1, 1, 2, 3, 5, 8, 13, 21 ......
代码:
//有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?
package demo01;
import java.util.Scanner;
public class HelloJava {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入月份:");
int month = sc.nextInt();
sc.close();
if(month >= 1) {
System.out.println("第" + month + "个月的兔子对数为:" + rabbitNumber(month) + "对!");
}else {
System.out.println("您输入的月份不合法!");
}
}
public static int rabbitNumber(int month) {
if(month == 1 || month == 2) {
return 1;
}else {
return rabbitNumber(month - 1) + rabbitNumber(month - 2);
}
}
}
运行结果: