-1

I am doing the Cash(less) problem in CS50 and my code will not print the number of coins that I have

I tried moving print into a do while loop but that made it print forever.

do
{
    for(int f = money;f >=0;f++)
    {
        for(q=0; money >= .25;q++)
         {
             money = money - .25;
         } 
        for(d=0; money >= .10;d++)
         {
             money = money - .1;
         } 
        for(n=0; money >= .05;n++)
         {
             money = money - .05;
         } 
        for(p=0; money >= .01;p++)
         {
             money = money - .01;
         } 

    }
  }while(money>=0);
        coins = q+d+n+p;
        printf("%f", coins);

It should print the minimum number of coins required to return change to a customer based on the input they put in earlier in the code.

1 Answers1

0

Because you are using floats you may be hitting a rounding error and ending up with money having a value like .001. This will cause you to enter the top level for loop again which will reset q,d,n, and p to 0. It is much cleaner to use while loops:

#include <stdio.h>
#include <stdlib.h>

main()
{
        int q = 0;
        int d = 0;
        int n = 0;
        int p = 0;
        float money = .34;  // test value
        int coins;

        while (money >= .25)
        {
                money = money - .25;
                q++;
        } 
        while (money >= .10)
        {
                money = money - .1;
                d++;
        } 
        while (money >= .05)
        {
                money = money - .05;
                n++;
        } 

        while (money >= .01)
        {
                money = money - .01;
                p++;
        }

        coins = q+d+n+p;
        printf("%d", coins);  // Note that type was changed to int
}

Note since this still uses floats you may get small rounding errors. It would be better to count by cents using integers instead of floats to track a fraction of a dollar but I wanted to keep a style similar to yours.

jmq
  • 1,559
  • 9
  • 21
  • I perfectly agree with the answer's last paragraph and recommend reading [this](https://floating-point-gui.de) and [this](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) about the issues of floating-point arithmetics. – Gerd Oct 17 '19 at 08:47