题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月
又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
由此我们写出代码如下:
如下代码
1 public class Interview1 {
2 public static void main(String[] args) {
3 System.out.print("please input month:");
4 Scanner input = new Scanner(System.in);
5 int month = input.nextInt();
6 int[] pairs = new int[month];
7 pairs[0] = 1;
8 pairs[1] = 1;
9 for (int i = 2; i < month; i++) {
10 pairs[i] = pairs[i - 1] + pairs[i - 2];
11
12 System.out
13 .println(i+1 + " month later have " + pairs[i]*2 + " rabbits");
14 }
15 }
16 }