zoukankan      html  css  js  c++  java
  • 关于大牛生小牛的问题

    问题:
              一只刚出生的小牛,4年后生一只小牛,以后每年生一只。现有一只刚出生的小牛,问20年后共有牛多少只?

    刚开始觉得递归比较好,想了很长时间,没想出来,于是想了下面一种方法来实现,先生成一个数据,并且数据第i个表示牛的年龄,数组i的值表示今年有几头牛,

    实现代码如下:

    const int YEAR = 50;

            static void Main(string[] args)
            {
              
                int[] yearAmount = new int[YEAR];
                yearAmount[0] = 1;
                for (int year = 1; year < YEAR; year++)
                {
                    int count = 0;
                    for (int i = year; i > 0; i--)
                    {
                        if (i >= 2)
                            count += yearAmount[i]; //可以生小牛的有几头

                        yearAmount[i] = yearAmount[i - 1]; //牛的年龄+1
                    }
                    yearAmount[0] = count; //生的小牛是0岁
                }

                int result = yearAmount.Sum();
                Console.WriteLine("{0}年总计:{1}头牛", YEAR, result);

                Console.Read();
            }

    速度还挺快!!!

  • 相关阅读:
    deb app install under terminal
    修改代理
    virtualenv install &usage
    what a pietty
    晚上想睡觉不要喝可乐
    ubuntu server 调教
    修改代理
    修改网关为静态IP
    infobright install tips
    i like fujishu laptop more than mac
  • 原文地址:https://www.cnblogs.com/benwu/p/2737596.html
Copyright © 2011-2022 走看看