您的位置:首页 > 编程语言 > C#

一个牧场目前一共有20头刚出生的羊,母羊、公羊各一半。假如母羊5岁时后每年生一胎(母羊,公羊各一半)。羊活到10岁后死亡。请问20年后这个牧场有多少只羊? 请用C#写出算法。

2016-05-17 12:25 543 查看
假设一胎生一只公羊和一只母羊。

实现代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace 多少只羊
{
class Program
{
static void Main(string[] args)
{
int sheepCount;
for (int i = 1; i <= 20; i++)
{
sheepCount = GetSheepCount(i) - GetDeathSheepCount(i);
Console.WriteLine(sheepCount);
}
}

private static int GetSheepCount(int year)
{
if (year <= 4)
return 20;
return GetSheepCount(year - 1) + GetSheepCount(year - 5) - GetDeathSheepCount(year);
}

private static int GetDeathSheepCount(int year)
{
if (year < 10)
return 0;
return GetSheepCount(year - 10);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: