The question of finding change is very clear, nothing more than always take the maximum face value to find, and finally make the number of the smallest, the implementation is to assume a variety of face value enough.
First drag out an interface, the bottom is a ListBox control
Corresponding code: The problem is relatively simple, there are comments
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)//The second calculation is emptied for easy re-calculation
ListMoney.Items.Clear ();
var money = Exchange (Convert.todecimal (Txtmoney.text));
foreach (Var)
{
if (single. Value! = 0)
{
string s = String. Format ("{0} meta---->{1}", single. Key, single. Value);
LISTMONEY.ITEMS.ADD (s);
}
}
}
Dictionary<decimal, int> getinit ()//initialization dictionary
{
Dictionary<decimal, int> money = new Dictionary<decimal, int> ();
Key means money, value represents the number of money
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]++; More than 0.05 of the time to give customers 0.1.
return money;
}
Else
return money; Otherwise, forget it.
}
var max = money. Keys.elementat (i); Get face value
if (num >= max)
{
num = Num-max;
Money[max] + +; Number of money self-increment
}
Else
i++; I'm going to take a face.
}
}
}
}
Greedy algorithm-Find change (C # Implementation)