Hey,

My homework assignment for my C++ class was to write a program that can find the minimum amount of coins necessary for change for a purchase.

Here's the code I came up with:

Code:

#include <iostream>
#include <string>
using namespace std;
void calculate ( double change, int * coins );
void getValues ( double &change );
int main ( int argc, char * argv[] )
{
string coinTypes[6] = { "Dollars", "Half-Dollars", "Quarters", "Dimes", "Nickels", "Pennies" };
int coinValues[6] = { 0, 0, 0, 0, 0, 0 };
double change = 0.0;
getValues ( change );
calculate ( change, coinValues );
for ( int i = 0; i < 6; i++ )
{
cout << coinTypes[i] << " = " << coinValues[i] << endl;
}
system("pause");
return 0;
}
//
//Function to get the values from the user
//
void getValues ( double &change )
{
double total, paid;
cout << "Enter total cost: ";
cin >> total;
cout << "Enter amount paid: ";
cin >> paid;
change = static_cast<double>(paid - total);
}
//
//function to calculate how many coins are needed
//
void calculate ( double change, int * coins )
{
double div[] = { 1, .5, .25, .1, .05, .01 };
double result;
//Figire out the number of coins needed;
for ( int i = 0; i < 6; i++ )
{
result = static_cast<double>( change / div[i] ); //see how many of the coin value go into the change amount
change -= static_cast<double>( (int)result * div[i] ); //subtract the value of the coin * the amount of it from the change
coins[i] = static_cast<int>( result ); //take the number of coins and store in the necessary variable
}
}

Here's the program's output

Code:

Enter total cost: 56.78
Enter amount paid: 100
Dollars = 43
Half-Dollars = 0
Quarters = 0
Dimes = 2
Nickels = 0
Pennies = 1
Press any key to continue . . .

Everything is good except there should be 2 pennies, not 1...

I think there's some sort of precision error or something in the numbers.

Any help would be greatly appreciated.

Thanks,

Matt N