I need to make a simple C++ program that asks the user to enter any amount of money, and then show the user how to pay the specified amount using the smallest number of 50,20,10,5,1 units of money. In the context of my program, the unit of money used is Rands.

Below is my code which makes sense to me, however I yield an unexpected output. Does anyone know why?

Thanks

//File: change.cpp
#include <iostream>
using namespace std;
int amount = 0;
int main(void){
    cout << "Enter a Rands Amount:\n";
    int fifties, twenties, tens, fives, ones=0;
    cin >> amount;

    while ((amount - 50)>=0){
        fifties = fifties +1;
        amount = amount - 50;
    }
    cout << "R50 Notes: " << fifties << "\n";

    while ((amount - 20)>=0){
        twenties = twenties +1;
        amount = amount - 20;
    }
    cout << "R20 Notes: " << twenties << "\n";

    while((amount-10)>=0){
        tens = tens+1;
        amount = amount - 10;
    }
    cout << "R10 notes: " << tens << "\n";  

    while((amount-5)>=0){
        fives = fives+1;
        amount = amount - 10;
    }
    cout << "R5 coins: " << fives << "\n";  

    while((amount-1)>=0){
        ones = ones+1;
        amount = amount - 1;
    }
    cout << "R1 coins: " << ones << "\n";   

}

When executing this code with the input 93, i expect the following output:

-R50 Notes: 1 -R20 Notes: 2 -R10 notes: 0 -R5 coins: 0 -R1 coins: 3

instead, I receive the following output:

-R50 Notes: 1 -R20 Notes: 2089938002 -R10 notes: 32767 -R5 coins: 0 -R1 coins: 3

All help is greatly appreciated

有帮助吗?

解决方案

This line:

int fifties, twenties, tens, fives, ones=0;

only initializes ones. You need to initialize each of the other variables.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top