1

I wrote this code and it's not working at all

I hope my explaining is good .

So what I need from the "for" loop is to continue to the last condition I had. and at the end print the counter number

{


//to do math
    float quarters = 0.25;
    float dimes  = 0.10;
    float nickels  = 0.5;
    float pennies  = 0.1;

//the number I need to transfer to 0
    float n = 0.65;

//the counting number
    int count = 0;
    
    for (;;)
    {
       if (n >= quarters ) // -0.25
        {
            n =  n - quarters;
            count += 1;
            return n ;
        }
        else if (n >= dimes) // -0.10
        {
            n =  n - dimes;
            count += 1;
            return n ;
        }
        else if (n >= nickels) // 0.5
        {
            n =  n - nickels;
            count += 1;
            return n ;
        }
        else if (n >= pennies) // 0.1
        {
            n =  n - pennies;
            count += 1;
            return n ;
        }
        else //return the counting number
        {
            printf("%i",count);
            break;
        }
    }
}
Bilker1422
  • 33
  • 4
  • 2
    What is it supposed to do, and what happens instead? – Mureinik Aug 28 '20 at 17:32
  • just counting how much time u need to Transfer N to 0 – Bilker1422 Aug 28 '20 at 17:37
  • 1
    What's with the `aaa...`s? – Fiddling Bits Aug 28 '20 at 17:57
  • 2
    For "change" problems" please use integer values - work in cents. Please read [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) `float dimes = 0.10;` cannot be *exactly* represented in binary to `int dimes = 10` can. – Weather Vane Aug 28 '20 at 17:57
  • You cannot start a C code file with an open `{`. Please, complete it to a [minimum, verifiable](https://stackoverflow.com/help/minimal-reproducible-example) code that shows the observed problem (and describe what is the expected behaviour and the one you have instead) – Luis Colorado Aug 29 '20 at 18:56

1 Answers1

3

Do not return n, use continue instead - continue will tell your loop to go another round and that is what you want here in order to go through the conditional logic again.

return terminates your function, so your program exits before reaching the final else branch where you would print out the counter.

Also, your pennies are set as 0.1, the same as dimes, and should be set to 0.01, I assume.

EDIT: Per comment of Weather Vane posted under the question, it might be better to use integers for this problem, due to the misrepresentation of 0.01 in floating point. The SO question he has linked: Why not use Double or Float to represent currency?

kiwibg
  • 334
  • 2
  • 9