題目:古典問題:有一對兔子,從出生後第3個月起每月都生一對兔子,小兔子長到第三個月後每月又生一對兔子,假如兔子都不死,問每月的兔子總數爲多少?
程序分析: 兔子的規律爲數列1,1,2,3,5,8,13,21….code
class Program { //程序分析第三個月開始,兔子每個月數量=前兩個月兔子數量之和。 static void Main(string[] args) { int month = 0; //定義月份 Console.Write("輸入月份:"); //提示輸入須要計算幾個月 month=Convert.ToInt32(Console.ReadLine()); //讀取輸入的月份 int temp1 = 1; //前2個月兔子數量. int temp2 = 1; //前1個月兔子數量 for(int i=1;i<=month;i++) { if (i == 1) { //第一個月兔子數量 Console.WriteLine("第" + i + "月兔子數量爲:1"); } else if (i == 2) { //第二個月兔子數量 Console.WriteLine("第" + i + "月兔子數量爲:1"); } else { //第三個月開始是前兩個月之和 int total = 0; total = temp1 + temp2; temp1 = temp2; temp2 = total; Console.Write("第" + i + "月兔子數量爲:"); Console.WriteLine(total); } } Console.ReadKey(); } }