Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm số tờ tiền tối thiểu để trả số tiền cho trước trong C++

Cho số tiền, tìm số tờ tiền tối thiểu (giá trị lớn nhất trước) từ tập {2000,500,200,100,50,20,10,5,2,1}. Ví dụ: 800 → 500, 200, 100.

Thuật toán tham lam: duyệt từ mệnh giá lớn, lấy số tờ = tiền / mệnh giá, cập nhật tiền dư.

Ví dụ

#include <iostream>
using namespace std;

void countNotes(int amount) {
    int notes[10] = {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
    int noteFreq[10] = {0};
    for (int i = 0; i < 10; i++) {
        if (amount >= notes[i]) {
            noteFreq[i] = amount / notes[i];
            amount -= noteFreq[i] * notes[i];
        }
    }
    cout << "Note count:\n";
    for (int i = 0; i < 10; i++) {
        if (noteFreq[i] != 0)
            cout << notes[i] << " : " << noteFreq[i] << endl;
    }
}

int main() {
    int amount = 1072;
    cout << "Total amount is: " << amount << endl;
    countNotes(amount);
}

Kết quả

Total amount is: 1072
Note count:
500 : 2
50 : 1
20 : 1
2 : 1