CS50现金有效输入退出程序

时间:2018-09-03 13:30:26

标签: c while-loop return-value do-while cs50

我不确定为什么我的找零值永远不会在第二个循环中求值,也不知道我的打印语句最终不会输出硬币。输入有效输入后,程序应将浮点数转换为int并输入下一个while循环。然后,根据更改值,应检查每个if语句中的条件是否为true,直到while条件为false为止。

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

1 个答案:

答案 0 :(得分:2)

问题来自return coins;循环内的while行。

您应该编写类似的内容:

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;