貪心演算法-找零錢(C#實現)

來源:互聯網
上載者:User

標籤:

找零錢這個問題很清楚,無非就是始終拿可以取的最大面值來找,最後就使得張數最小了,這個實現是在假設各種面值足夠多的情況下。

首先拖出一個介面來,最下面是一個listbox控制項

 

對應的代碼:問題比較簡單,有注釋

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (listMoney.Items.Count != 0)   //第二次計算就清空,便於重複計算
                listMoney.Items.Clear();

            var money = Exchange(Convert.ToDecimal(txtMoney.Text));


            foreach (var single in money)
            {
                if (single.Value != 0)
                {
                    string s = string.Format("{0}元---->{1}張 ", single.Key, single.Value);
                    listMoney.Items.Add(s);
                }
            }

        }
        Dictionary<decimal, int> GetInit()  //初始化字典
        {
            Dictionary<decimal, int> money = new Dictionary<decimal, int>();

            //key表示錢,value表示錢的張數
            money.Add(100.00M, 0);
            money.Add(50.00M, 0);
            money.Add(20.00M, 0);
            money.Add(10.00M, 0);
            money.Add(5.00M, 0);
            money.Add(2.00M, 0);
            money.Add(1.00M, 0);
            money.Add(0.50M, 0);
            money.Add(0.20M, 0);
            money.Add(0.10M, 0);

            return money;
        }

        Dictionary<decimal, int> Exchange(decimal num)
        {
            var money = GetInit();

            int i = 0;

            while (true)
            {
                if (num < 0.1M)
                {
                    if (num > 0.05M)
                    {
                        money[0.10M]++; //大於0.05的時候給顧客0.1.
                        return money;
                    }
                    else
                        return money;  //否則就算了
                }

                var max = money.Keys.ElementAt(i);  //取得面值

                if (num >= max)
                {
                    num = num - max;
                    money[max] ++;   //money的張數自增
                }
                else
                    i++;  //就去取下一張面值
            }
        }
    }
}

貪心演算法-找零錢(C#實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.