0

how you doing? I can't figure out where is the bug from my code :/ It's really strange and the results are not the same if you do the same test with "0.01", for instance...

#include <stdio.h> #include <cs50.h> #include <math.h>

int main(void) { float c;

//asking the user for the change
do
{
    c = get_float("change owed: ");
}
while (c < 0);

//converting it from cents to dollars
int d = round (c * 100);

//number of coins
int k;

do
{
    //quarters
    if (d >= 25)
    {
        k = d / 25;
        d = d % 25;
    }
    
    //dimes
    if (d < 25 && d >= 10)
    {
        k = k + d / 10;
        d = d % 10;
    }
    
    //nickels
    if (d < 10 && d >= 5)
    {
        k = k + d / 5;
        d = d % 5;
    }
    
    //pennies
    if (d < 5 && d >= 1)
    {
        k = k + d / 1;
        d = d % 1;
    }
}
while (d > 0);

printf("%i\n", k);

}

0

If it's really strange and gives unpredictable results, it is probably because k is not initialized. In the ".01" example, with k not initalized, there is no way to predict what the outcome of this statement k = k + d / 1; will be. It will add whatever is in k's memory address to d / 1. Initialize k, i.e. set it to something, when it is declared here int k;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .