題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?
程序分析: 兔子的規律為數列1,1,2,3,5,8,13,21….
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();
}
}
