可以考虑用多线程写,递归做法只是让奶牛每次只能有一个一个去生,其他的等她生完了再去生而已。
如果是多核CPU,那么奶牛如何知道自己是几岁,今年生了没有。
哈哈,其实简单的问题,要是细细推敲起来,也是非常有意思的。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Cow
{
class Program
{
static void Main(string[] args)
{
int iYear=0;
new Thread(new Cow().Growth).Start();
while (iYear < 20)
{
iYear++;
Console.WriteLine(iYear.ToString()+" years: "+Cow.iTotal);
Thread.Sleep(1000);
}
Environment.Exit(0);
}
}
class Cow
{
public static int iTotal = 0;
int iAge = 0;
public Cow()
{
iTotal++;
}
public void Growth()
{
while (true)
{
iAge++;
if (iAge >= 4)
{
new Thread(new Cow().Growth).Start();
}
Thread.Sleep(1000);
}
}
}
}
为什么多出来好多??
@fffly
对啊,有时候小问题,大学问,呵呵
@silent x
好像蛮长的,我看看;)
@周银辉
确实挺费时间的,我算法较差,非递归真的写不出来,我看看你的算法。
我用递推一样的做出来了,,代码就只有二三十行,,,当然没有代码没有多优化,不过,,这里数字小,,,做出来就行!!