简体   繁体   中英

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

}

Roundoff error:

When the machine stores 4.2, it is not exactly 4.2. Thus, when multiplied by 100, it gets to 419.99999..., which converts to the int 419. The way to fix this would be:

int change1 = change * 100 + 0.5;

This could also be checked by

printf("%i\n", change1)

after the calculation.

Hum i just want you show to prefer use ternary operator in this situation :

     #include <stdio.h>

     int     main() {   
    float number;   
    int   result;   
    int   ctn_coin;

       ctn_coin = 0;   
     printf("How much change do you want?\n");  
     scanf("%f", &number);   result = number * 100.1;

       while (result != 0)
         {
           result >= 25 ? result -= 25 :
             result >= 10 ? result -= 10 :
             result >= 5 ? result -= 5 :
             result >= 1 ? result -= 1 : 0;
           ctn_coin++;
        }   
   printf("%i\n", ctn_coin);   
   return (0); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM