【C#】[算法]百鸡算法(母鸡+公鸡+小鸡=100)

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

namespace 百鸡算法
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             *题目:母鸡每只3元,公鸡每只2元,小鸡每只0.5元,计算一下如何100块钱买100只鸡。
             *分析:
             *      我们用三个Int变量来代表母鸡(hens)、公鸡(cocks)、小鸡(chicks)的个数。
             *      母鸡+公鸡+小鸡=100
             *      (母鸡x3)+(公鸡x2)+(小鸡x0.5)=100
             *      那么其中母鸡最多只会有100÷3=33只、公鸡最多100÷2=50只、小鸡最多100÷0.5=200只
             *      所以还要满足 0≥母鸡≤33 | 0≥公鸡≤50 |  0≥小鸡≤200 
             */

            Console.WriteLine("题目:母鸡每只3元,公鸡每只2元,小鸡每只0.5元,如何100块钱买100只鸡。\n");
            Console.WriteLine("母鸡  公鸡  小鸡");
            int hens, cocks, chicks; //定义Int变量:母鸡,公鸡,小鸡
            for (hens = 0; hens <= 33; hens++)//循环:母鸡的只数
            {
                for (cocks = 0; cocks <= 50 - hens; cocks++)//循环:公鸡的只数(0 到 (50-hen))
                {
                    chicks = 100 - hens - cocks;//满足百鸡条件:小鸡(chicks)就等于100-母鸡数(hens)-公鸡数(cocks)
                    if (hens * 3 + cocks * 2 + chicks * 0.5 == 100)//满足价钱条件:(母鸡x3)+(公鸡x2)+(小鸡x0.5)=100
                    {
                        Console.WriteLine("{0}     {1}     {2}   =  100只", hens, cocks, chicks);//输出母鸡公鸡小鸡数
                    }
                }
            }
            Console.Read();
        }
    }
}
posted @ 2011-01-25 13:17  isaced  阅读(1154)  评论(1编辑  收藏  举报