CS50 现金有效输入退出程序

CS50 Cash valid input exits program

我不确定为什么我的找零值在第二个循环中从未被评估过,我的打印语句 运行 在最后也没有输出硬币。输入有效输入后,程序应将浮点数转换为 int 并进入下一个 while 循环。然后根据变化值应该检查每个if语句中的条件是否为真,直到while条件为假。

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

int main(void) {

    int coins = 0;
    float n;
    int change;
    do
    {
       n = get_float("How much do I owe you? \n");
    } while (n < 0); // continue prompt while true less than zero

    change = n * 100;

    while (change > 0)
    {
        if (change > 25) // change .25 cents
        {
             coins = coins + 1;
             change = change - 25;
        }
        else if (change > 5 && change <= 10)  // change 10 cents
        {
             coins = coins + 1;
             change = change - 10;
        }
        else if (change > 1 && change <= 5)  // change 5 cents
        {
             coins = coins + 1;
             change = change - 5;
        }
        else  // change 1 cents
        {
             coins = coins + 1;
             change = change - 1;
         }
        return coins;
      }
    printf("%d\n", coins);
}

问题出在 while 循环内的 return coins; 行。

你应该这样写:

while (change > 0) 
{
    /*update coins and change
      but do not use return.*/
}

printf("%d\n", coins);

/* as return will exit from your function, 
    you want it at the end*/
return coins;