/// <summary> /// 母牛 /// 有一个农场有一头成年母牛,每三个月后一头小牛,小牛一年后长大,长大后每三个月又可以生一头小牛, /// 如此循环,问n年后农场一共有多少牛? /// </summary> class Cattle { public int year; public int timeUint;//时间单位(3个月为一个单位) public int initialNum; public Cattle(int year) { this.year = year; this.timeUint = year * 4; //第一头母牛和它生的小母牛,为初始值。(每三个月生一头小牛,一年生4头小牛) this.initialNum = year * 4 + 1; } /// <summary> /// 方法一 /// </summary> /// <param name="timeunit"></param> /// <param name="num"></param> public void GetCattle(int timeunit,ref int num ) { //小牛生小牛需要5个时间单位。(小牛一年后长大,长大后每三个月又可以生一头小牛) //即拥有生育能力的小牛比上一代少5头。 int nextGeneration = timeunit - 5; for (int i = nextGeneration; i > 0; i--) { num += i;//下一代的数目 GetCattle(i, ref num);//下下一代 } } /// <summary> /// 方法二 /// </summary> /// <param name="time">时间单位</param> /// <returns></returns> public int CalcCattle(int time) { if (time <= 5) return time + 1; else return CalcCattle(time - 1) + CalcCattle(time - 5); } }
主函数
do { Console.WriteLine("请输入时间:"); int n = Convert.ToInt32(Console.ReadLine()); Cattle cattle = new Cattle(n); cattle.GetCattle(cattle.timeUint, ref cattle.initialNum); Console.WriteLine("方法一,第{0}年母牛的数量为{1}", n, cattle.initialNum); int num = cattle.CalcCattle(cattle.timeUint); Console.WriteLine("方法二,第{0}年母牛的数量为{1}", n, num); Console.WriteLine("是否继续,Y/N ?"); } while (Console.ReadLine().ToLower() == "y");