0

我有一个 do-while 循环:

float amount;
do
{
    printf("Input dollar amount owed:\n");
    amount = GetFloat();
}
while (amount <= 0); 

然后是一个while循环和printf:

int coins = 0;
while (amount >= 0.25);
{
    amount = amount - 0.25;
    coins++;
}
printf("Number of coins to use: %d\n", coins);
return 0;

但是当我运行并使用它时,while 循环不会运行并且 printf 不会打印。在我的终端中看起来像这样,其中 1 是用户输入:

输入欠款金额:1

如何让程序进入 while 循环和 printf?

4

3 回答 3

9
while (amount >= 0.25);
                      ^ roh roh

我想你的意思是:

while (amount >= 0.25)
{
    amount = amount - 0.25;
    coins++;
}

while(x);是相同的while(x) { }

于 2013-10-29T22:25:27.817 回答
1

This just looks like a syntax error in while (amount >= 0.25); it should be while (amount >= 0.25). just have to remove the semicolon.

于 2018-03-31T23:13:05.290 回答
0

似乎您想获取每个amount输入的硬币数量,直到输入负数。为此,您需要嵌套while循环。伪代码将是:

Get amount
Check if it is greater than 0
Get number of coins and print
Repeat

实际的代码可能是这样的:

float amount;
printf("Input dollar amount owed:\n");
amount = GetFloat();
while( amount >= 0 )
{
    int coins = 0;
    while (amount >= 0.25)
    {
        amount -= 0.25;
        coins++;
    }
    printf("Number of coins to use: %d\n", coins);

    printf("Input dollar amount owed:\n");
    amount = GetFloat();
}

return 0;

但是,您的“获得硬币数量”只是进行除法运算,然后进行地板运算。所以这不需要循环:

int coins = (int) (amount / 0.25f);   // casting to an int will truncate the float.
于 2013-10-29T22:40:50.330 回答