-4

I cannot get the method to output the last lines, help?

Tried the nested if statments, for and do whiles, while is my new default

double cashpay = 0.00;
int doll = 0;
double quart = 0.0;
double dime = 0.0;
double nic = 0.0;
double penn = 0.0;
int c = 0;
cout << "Please input a number less than 5.00: ";
cin >> cashpay;
if (cashpay <= 5.00) {
  while (c >= 0) {
    while (c / 1 != 0) {
      doll += 1;
      c -= 1;
    }
    while (c / .25 != 0) {
      quart += .25;
      c -= .25;
    }
    while (c / .1 != 0) {
      dime += .1;
      c -= .1;
    }
    while (c / .05 != 0) {
      nic += .05;
      c -= .05;
    }
    while (c / .01 != 0) {
      penn += 0.01;
      c -= .01;
    }
  }
  cout << " " << endl;
  cout << doll << " dollars, ";
  cout << quart << " quarters, ";
  cout << dime << " dimes, ";
  cout << nic << " nickles, and ";
  cout << penn << " pennies " << endl;
} else {
  cout << "Error. Please enter a number under 5.00" << endl;
}

only gives either the input and then possibly the greater than line, no more/less

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • 8
    Evil use of floating point types here. Work in cents and use integral types. Watch the bugs disappear. – Bathsheba Sep 16 '19 at 16:51
  • 1
    Be aware that there is also [std::ratio](https://en.cppreference.com/w/cpp/numeric/ratio/ratio) – nada Sep 16 '19 at 16:54
  • 1
    Related: [https://stackoverflow.com/questions/588004/is-floating-point-math-broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – drescherjm Sep 16 '19 at 17:01
  • 1
    OP, floating point math does not work as one would think it does. See dresherjm's comment. While 0.25 is exactly representable as a float, 0.1 for example isn't. – nada Sep 16 '19 at 17:05
  • You can try it yourself with this code snippet: https://wandbox.org/. Numbers are stored as binary numbers. Decimal 0.1 equals binary 0.00011001100110011... It can't be represented exactly. It is rounded and the result is not exact. Therefor `while (c / .1 != 0) {` will stay true. – Thomas Sablik Sep 16 '19 at 18:58

1 Answers1

2

In general, this problem is solved in the following pseudo-code:

Let there be four vars of unsigned int: quart(0), dime(0), nick(0), penn(0);
While THE AMOUNT OF CHANGE REMAINING is greater than $.00:
    Select the largest value ($.25) or ($.10) or ($.05) or ($.01) that is NOT GREATER than the AMOUNT OF CHANGE REMAINING;
    Increment quart or nick or dime or penn as above;
    Subtract the selected value from THE AMOUNT OF CHANGE REMAINING;
Return {quart, dime, nick, penn}.
C. R. Ward
  • 93
  • 5