【算法学习】贪婪算法找零钱

因为算法比较简单,就不罗嗦了,代码如下:


//贪婪算法解决找零钱

#include <iostream>
using namespace std;
#define NUM 8
static const int permoney[] = { 10000, 5000, 2000, 1000, 500, 100, 50, 10 };

void exchange(int* result,float money);

void main(){
    float money = 0;
    while (cin>>money){
        if (money == 0.0)
            return;
        int result[NUM];
        exchange(result,money);
        for (int i = 0; i < NUM; i++){
            if (result[i] != 0){    //如果当前需要的面值张数不为0,则输出
                cout<<permoney[i]/100.0<<"->"<<result[i]<<endl;
            }
        }
    }
}

void exchange(int* result,float money){
    int mi = money * 100;
    for (int i = 0; i < NUM; i++){      //从面值为100的算起
        int n = mi/permoney[i];         //需要几张100的
        mi = mi%permoney[i];            //还剩下多少钱要找
        result[i] = n;                  //记录下需要几张100的,跳转到下一面值的钱
    }
}


你可能感兴趣的:(C++,找零钱,贪婪算法)