question:假设有一种货币,它有面值为1分、2分、5分和1角的硬币,最少需要多少个硬币来找出K分钱的零钱。按照贪婪法的思想,需要不断地使用面值最大的硬币。如果找零的值小于最大的硬币值,则尝试第二大的硬币,依次类推。
/*程序的版权和版本声明部分:
**从《C++程序设计思想与方法》(作者:翁惠玉)P61转载
*/
#include <iostream> using namespace std; #define ONEFEN 1
#define TWOFEN 2
#define FIVEFEN 5
#define ONEJIAO 10 int main(void)
{
int money;
int onefen = , twofen = , fivefen = , onejiao = ; cout << "输入要找零的钱(以分为单位):";
cin >> money; //不断尝试每一种硬币
while(money >= ONEJIAO)
{
onejiao++;
money = money - ONEJIAO;
}
while(money >= FIVEFEN)
{
fivefen++;
money = money - FIVEFEN;
}
while(money >= TWOFEN)
{
twofen++;
money = money - TWOFEN;
}
while(money >= ONEFEN)
{
onefen++;
money = money - ONEFEN;
} cout << "1角硬币数:" << onejiao << endl;
cout << "5分硬币数:" << fivefen << endl;
cout << "2分硬币数:" << twofen << endl;
cout << "1分硬币数:" << onefen << endl; return ;
}