简体   繁体   English

while循环中的if语句未在C中给出预期的输出

[英]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. 我将所需的更改作为正浮点数,然后乘以100将其转换为整数,以使金额为几美分。 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. 经过测试,某些值有效,而其他值(如4.2)则无效,给出的答案应为22(应为18)。我无法弄清原因。 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. 机器存储4.2时,它并不完全是 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: 因此,当乘以100时,它将变为419.99999 ...,它将转换为int419。解决此问题的方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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