...

View Full Version : Help with simple C++ functions

Derek Zoolander
10-24-2007, 09:49 PM
I wrote a simple program to determine the least amount of change for a given input, but I need to use a function prototype and incorporate a separate MakeChange function to perform the calculations and return the values.
This is the simple program using one main function:

#include <iostream>
#include <iomanip>

using namespace std;
int main()
{
int amounttochange=1;
int dollars, cents;
int quarters, dimes, nickels, pennies;

while(amounttochange!=0)
{
cout << "Enter dollar amount: ";
cin >> dollars;
cout << "Enter cents: ";
cin >> cents;

//Do calculations
amounttochange = (dollars*100)+cents; //convert to cents
quarters = amounttochange/25;
dimes = (amounttochange%25)/10;
nickels = ((amounttochange%25)%(10))/5;
pennies = (((amounttochange%25)%(10)%(5)))/1;

//Output coins
cout << "Quarters: " << quarters <<endl;
cout << "Dimes: " << dimes <<endl;
cout << "Nickels: " << nickels <<endl;
cout << "Pennies: " << pennies <<endl;
}
return 0;
}

How can I convert this to use two functions: main and MakeChange? it should take in a value like .86 and return 3 quarters, 1 dime, 1 penny.
amounttochange must be of type double (I don't know how to do double divided by int?). quarters, dimes, nickels, pennies must be of type int.

Will it look something like this?:

#include <iostream>
#include <iomanip>

using namespace std;

int MakeChange(double amounttochange, int quarters, int dimes, int nickels, int pennies);
int main(?) //do i need any parameters here?
{
while(double amounttochange!=0)
{
cout << "Enter the amount to change (enter 0 to end program): ";
cin >> amounttochange;

cout << "Quarters: " << MakeChange(?) <<endl; //? is returned from MakeChange(), right?
cout << "Dimes: " << MakeChange(?) <<endl;
cout << "Nickels: " << MakeChange(?) <<endl;
cout << "Pennies: " << MakeChange(?) <<endl;
}

return 0;
}

int MakeChange(double amounttochange, int quarters, int dimes, int nickels, int pennies)
{
//calculations here
return ?; //I don't know how to return multiple values for quarters, dimes, etc.
}

ralph l mayo
10-25-2007, 04:37 AM
There are several ways to do this, returning a pointer to an array being among the least preferable. The instructor/text is probably hoping to see you use a struct:

struct Change
{
int quarters, dimes, nickles, pennies;
};

Change MakeChange(double amt);

oracleguy
10-25-2007, 04:51 AM
You could also pass the quarters, dimes, nickel (you could never have more than 1 nickel) and pennies by reference to your MakeChange function.