C#基础练习之换硬币

换硬币问题

         * 编程求:把一张1元的钞票换成5分,2分和1分的硬币,要求每种至少一枚,
         * 并且所换硬币数不超过30枚。请问有哪几种换法。
         * 
         * 需求分析:    1.1元=100分
         *               2.三元方程求解不等式
         *                      5x+2y+z = 100;   
         *                      x+y+z <=30;
         *                      x,y,z>=1;

以下是C#代码实现:


//三层for循环中定义三个变量fiveCentCoin,twoCentCoin,oneCentCoin分别表示5分,2分,1分硬币的数量穷举
            //定义一个计数器统计有多少种换法
            int count = 0;

            //第一层for控制5分硬币数量
            for (int fiveCentCoin = 1; fiveCentCoin <= 18; fiveCentCoin++)
            {
                //第二层for控制2分硬币数量
                for (int twoCentCoin = 1; twoCentCoin <= 28; twoCentCoin++)
                {
                    //第三层for控制1分硬币数量
                    for (int oneCentCion = 1; oneCentCion <= 28; oneCentCion++)
                    {
                        if (fiveCentCoin + twoCentCoin + oneCentCion <= 30 
                            && 5*fiveCentCoin + 2*twoCentCoin + oneCentCion == 100)
                        {
                            //计数且输出合适方案
                            count++;
                            Console.WriteLine("第{0}种换法:{1}枚5分,{2}枚2分,{3}枚1分;",count,fiveCentCoin,twoCentCoin,oneCentCion);
                        }
                    }
                }
            }

            //输出总共有多好种方案
            Console.WriteLine("总共有{0}中方案。",count);
            

好了,这个问题就到这里,有疑问的可以私信博主。

纯手打。
给个关注呗!

发布了25 篇原创文章 · 获赞 4 · 访问量 1734

猜你喜欢

转载自blog.csdn.net/maybe_ice/article/details/104329760