生兔子问题

很有意思的面试题大家快来看看
 一对小兔子一年后长成大兔子;一对大兔子每半年生一对小兔子。大兔子的繁殖期为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/archive/2013/01/04/2844522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值