Bilker1422
Bilker1422

Reputation: 33

Does anyone know what is the problem in this code? it's not work at all

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;
        }
    }
}

Upvotes: 1

Views: 68

Answers (1)

kiwibg
kiwibg

Reputation: 334

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?

Upvotes: 3

Related Questions