題目:
/**
* 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,
* 小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個
* 月的兔子總數為多少?
*
*/
解析:
/**
* 1.這是一個斐波那契數列,第三個數等於前兩個數之和
* 2.定義變量,第一個數,第二個數,第三個數,都會隨着月數的變化而變化
* 總而言之就是動態的
* 第一,第二,第三都是相對的
*/
public class Programmer1 { public static void main(String[] args) { /** * 1.這是一個斐波那契數列,第三個數等於前兩個數之和 * 2.定義變量,第一個數,第二個數,第三個數,都會隨着月數的變化而變化 * 總而言之就是動態的 * 第一,第二,第三都是相對的 */
int first = 1; int second = 1; int third ; for(int month=1;month<25;month++){ if(month>2){ third = first +second; first = second; second =third; System.out.println("第"+month+"個月有"+third+"對兔子"); }else{ System.out.println("第"+month+"個月有"+first+"對兔子"); } } System.out.println("-------------------------用數組實現---------------------"); /** * 用數組實現菲波那切數列數列 * 1.定義一個數組來存儲兔子的對數 * 2.第一,第二個數賦值為1 * */
int[] arr = new int[24]; arr[0]=1; arr[1]=1; for(int i=2;i<arr.length;i++){ arr[i]=arr[i-1]+arr[i-2]; System.out.println("第"+(i+1)+"個月有"+arr[i]+"對兔子"); } } }
結果:
第1個月有1對兔子
第2個月有1對兔子
第3個月有2對兔子
第4個月有3對兔子
第5個月有5對兔子
第6個月有8對兔子
第7個月有13對兔子
第8個月有21對兔子
第9個月有34對兔子
第10個月有55對兔子
第11個月有89對兔子
第12個月有144對兔子
第13個月有233對兔子
第14個月有377對兔子