Need help with C++ program

I need this program to calculate the most efficient amount of change currently for a value entered does not work, what should I do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include "stdafx.h"
using namespace std;

int main()
{

	double x;
	int y;
	cout << " enter the quantity: " << endl;
	cin >> x;
	y = x * 100;
	cout << " You will need " << y / 25 << " quaters ";
	y = y % 25;
	cout << " , " << y / 10 << " dimes ";
	y = y % 10;
	cout << " , " << y / 5 << " nickels ";
	y = y % 5;
	cout << " , " << y / 1 << " pennies ";

	return 0;
}
Please explain the "does not work". What is wrong?

(I can see at least one obvious flaw and one potential issue, but we wan't you to explain the problem in detail. That explanation might even lead you to a solution.)
If you enter 4.56, you'll see slightly incorrect output:
 enter the quantity:
4.56
 You will need 18 quaters  , 0 dimes  , 1 nickels  , 0 pennies

The problem is line 12 where the result of x*100 gets truncated. Due to floating point rounding errors, you should round this off instead:
1
2
3
#include <cmath>
...
y = round(x*100);


Also note that it will give "0 dimes". Ideally, you shouldn't print this at all, so you'd need something like
1
2
3
4
if (y>10) {
    cout << " , " << y / 10 << " dimes ";
    y = y % 10;
}

Now the code is starting to look VERY repetitive, so consider writing a function to factor out the common code. For example:
1
2
3
4
5
6
7
8
9
// Given some number of cents, the value of a coin and the name of
// the coin, print out the number of coins needed for the change
// If no coins are needed then print nothing.  Returns the new
// number of cents leftover after the change has been given
int
makeChange(int cents, int coinValue, const string &coinName)
{
    // INSERT YOUR CODE HERE
}
Topic archived. No new replies allowed.