while循环运行一次迭代

时间:2015-03-22 05:30:06

标签: c loops while-loop

#include <stdio.h>

int main (void)
{
    int cash,num10s,change;

    printf("please enter the amount you wish to withdraw\n");
    scanf("%d", &cash);

    num10s = (cash / 10);
    change = (cash % 10);
    printf("%d",change);

    while (change != 0);
    {
        printf("please enter a value in 10s\n");
        scanf("%d",&cash);
        change = (cash % 10);
    }

    printf("sucess\n");

    return (0);
}

即使更改值为0,while循环仍将运行一次迭代。为什么这样,我该如何缓解这个问题

4 个答案:

答案 0 :(得分:4)

您的代码中存在拼写错误。 变化

while (change != 0);

while (change != 0)

;循环之后的while导致循环无限运行,因为 while (change != 0)也可以写成

while (change != 0) {}

答案 1 :(得分:2)

因为在while循环关闭括号后你有一个分号。

答案 2 :(得分:1)

这是我最大的理由说明你不应该把花括号放在自己的行上

while (change != 0);
{ 
  printf("please enter a value in 10s\n");
  scanf("%d",&cash);
  change = (cash % 10);
}

看起来不错,但是在while语句之后真的是分号意味着它与

相同
while (change != 0) {
  // do nothing
}
printf("please enter a value in 10s\n");
scanf("%d",&cash);
change = (cash % 10);

如果你只把你的大括号放在与它的关键字相同的行上,那么你会看到while (...) {function(...);之间的差异更大,并且添加分号的机会更少结束了while循环中的“空块”。

答案 3 :(得分:1)

在while语句的末尾有一个分号,它终止了该行本身的while语句。将while语句更改为while(change! =0){}

相关问题