生兔子问题

很有意思的面试题大家快来看看
 
一对小兔子一年后长成大兔子;一对大兔子每半年生一对小兔子。大兔子的繁殖期为4年,兔子的寿命是6年。假定第一年年初投放了一对小兔子,

试编程计算,第n年末总共会有多少对兔子。n由键盘输入(请针对面向对象编程)

兔子类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication2
{
    class rabbit
    {
        private double year;
       
        public double Year
        {
            get { return year; }
            set { year = value; }
        }
        private int dai;
 
        public int Dai
        {
            get { return dai; }
            set { dai = value; }
        }
 
 
 public rabbit(int jidai)
 {
     this.Dai = jidai;
}  
       
 
    }
}
 
调用类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
    {
            Console.Write("年份:");
string Sinput = Console.ReadLine();
double dyear;
if(double.TryParse(Sinput,out dyear))
            {
Program fs = new Program();
int count = fs.GetNum(dyear);
Console.WriteLine("{0}年兔子总数:{1}只",dyear,count);
}
else
            {
 
Console.WriteLine("您输入的有误");
 
}
}
     
     
       
        private int era = 1;
private List<rabbit> ralist;//总兔子放在这里
private double startTime;
 
public  Program()
        {
ralist = new List<rabbit>();
ralist.Add(new rabbit(this.era));
            ralist.Add(new rabbit(this.era));//是一对兔子,所以填两只
}
 
public int GetNum(double Year)
        {
if(Year-this.startTime<=0.0){
return ralist.Count;//返回有几许对兔子
}
 
            //在生育期的兔子
 
List<rabbit> nrs = ralist.FindAll(r=>r.Year>=1.5&&r.Year<=5.5);
 
if(nrs.Count>0)
            {
this.era++;//生兔子,兔子总数,兔子代数
}
for(int i=0;i<nrs.Count;i++){
               
ralist.Add(new rabbit(this.era));//将新出生的小兔子添加到原兔子
}
nrs.Clear();//清空本年份的计算
           
            //大于六年的兔子死掉了
 
int killNum = ralist.RemoveAll(r=>r.Year>=6.0);
         
 
this.startTime += 0.5;//开始时间增长
foreach(rabbit rt in ralist){
rt.Year+=0.5;//所有兔子长了
}
return GetNum(Year);//递归调用
}
     
    }
}
原文地址:https://www.cnblogs.com/weiwin/p/2844522.html