1. 程式人生 > >題目:有一對兔子,從出生第三個月起每個月都生一對兔子,小兔子長到第三個月後,每個月又生一對兔子,假如兔子都不死,問M個月時兔子的數量,M為鍵盤讀入的正整數。(請用java語言作答)

題目:有一對兔子,從出生第三個月起每個月都生一對兔子,小兔子長到第三個月後,每個月又生一對兔子,假如兔子都不死,問M個月時兔子的數量,M為鍵盤讀入的正整數。(請用java語言作答)

樣例輸入:3樣例輸出:第1個月的兔子對數:1第2個月的兔子對數:1第3個月的兔子對數:2

import java.util.Scanner;

/**
* @author ForeverLover
*/
public class Rabbit {
public static void main(String[] args) {
long s1 = 1;
long s2 = 1;
int count;
long temp;
Scanner in = new Scanner(System.in);
count = in.nextInt();
for (int i = 1; i <= count; i++) {
if (i == 1) {
System.out.PRintln("第" + i + "個月的兔子對數:" + s1);
continue;
} else if (i == 2) {
System.out.println("第" + i + "個月的兔子對數:" + s2);
continue;
} else {
temp = s2;
s2 = s1 + s2;
s1 = temp;
System.out.println("第" + i + "個月的兔子對數:" + s2);
}
}
}
}
注:這涉及到的是斐波那契數列,公式:S(n)=S(n-1)+S(n-2)

  所謂斐波那切數列,又稱黃金分割數列,是指這樣的一個數列0、1、1、2、3、5、8、13、21、34、&hellip;…(

當然我們這裡是從1開始),