I am new to C++ programming and have a final project due tomorrow (Monday 12/9/13). This code should take a dollar amount entered and convert that into coins. I have most of this written and I get an error that the .exe has stopped working and I have no idea why. HELP!!
#include <iostream>
using std::cin;
using std::cout;
using std::fixed;
using std::endl;
#include <iomanip> // parameterized stream manipulators
using std::setprecision; // set numeric output precision
void ConvertToCoins(double);
int main ( )
{
double amount;
while(true)
{
// My added code to request the user to enter the dollar amount to convert
cout << "Enter the dollar amount you wish to convert to coins :\n";
// used to request user input of dollar amount
if(amount < 0) break;
ConvertToCoins(amount);
}
return 0;
}
void ConvertToCoins (double amt)
{
static int quarters = 0;
static int dimes = 0;
static int nickles = 0;
static int pennies = 0;
1. Compile your code with warnings on: g++ -Wall main.cpp -o main
2. "amount" is used but not initialized on line 20. which means that you should call cin before you try to use this variable. cin >> amount;
3. After I got the user input properly I noticed that your output was wrong. You are using static variables, which I would highly discourage. I would have recommended using an array and passing it through the recursion.
4. You messed up your if topology on the line: if(amt >= .05)
That should probably be an else if.
5. Because you are using static variables, Your output will only be correct the first time. Because the second time that that function is called, it will save the values from the last execution. The most simple (yet messy) fix to this is to put an if statement at the end of your function that checks to see if you are done (amt == 0). If done, set the quarters, dimes, nickels, pennies back to 0.
6. EDIT: Upon further inspection, I noticed that when you run this with certain numbers, it will STILL fail because of the limited percision of the double type. To overcome this, you should probably test for if( amount < 0.01) instead of amt == 0--under certain circumstances amount will never actually hit 0. This occurs when the number cannot be approximated exactly and never actually hits 0 as a result.
7. EDIT: I finally figured out what the final issue was--you need to have a final case in there where you check (after you check for if you have 0.01) if your number is still not 0, because if it isn't then you need to count that as a penny. Otherwise, your results will be off by a penny each time. The resetting of the coing counts can happen here or in an else statement.
Your code was messed up because you double recursed. This happened because you used an if instead of an else if. This is a perfect example of what will happen when you don't use else if when you were supposed to :). I got it working after I made those changes.
Note, never post code w/o putting it into the code tags.