lundi 27 mars 2017

If statements within while loop not giving expected output in C

I am making programme to calculate the maximum amount of coins in change given a set amount of change. I take the change demanded as a positive float and convert it into an int by multiplying it by 100, so that the amount is in pennies. Upon testing, some values work but others, such as 4.2, do not, giving the answer 22 when it should be 18. I cannot work out why. Could some please help.

int main (void) 

{

float change;

do 
{

    printf("How much change do you want?\n");
    change = get_float();  

} while (change < 0);

int change1 = change * 100;

int coins = 0;

while (change1 != 0)

{

    if (change1 >= 25)

    {
        change1 -= 25;
        coins++;
    }

    else if (change1 >= 10)

    {
        change1 -= 10;
        coins++;
    }

   else if (change1 >= 5)

    {
        change1 -= 5;
        coins++;
    }

    else if (change1 >= 1)

    {
        change1 -= 1;
        coins++;
    }


}

//Print change
printf("%i\n", coins);

}

Aucun commentaire:

Enregistrer un commentaire