【问题标题】:while loop runs one iteration regardlesswhile 循环运行一次迭代,不管
【发布时间】:2024-12-06 16:10:02
【问题描述】:
#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 循环仍会运行一次迭代。为什么会这样,我该如何缓解这个问题

【问题讨论】:

    标签: c loops while-loop


    【解决方案1】:

    您的代码中有错字。 改变

    while (change != 0);
    

    while (change != 0)
    

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

    while (change != 0) {}
    

    【讨论】:

      【解决方案2】:

      因为在 while 循环右括号之后有一个分号。

      【讨论】:

      • 很好的答案,但也许您应该进一步扩展您的答案。 +1 是 缓慢而稳定的 :)
      【解决方案3】:

      这是我声明您不应该将花括号放在自己的行上

      的最大理由之一
      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循环中。

      【讨论】:

      • 当我在抱怨大括号的放置时,} else { 而不是三行“else”,我不喜欢磨损我的滚动条并且屏幕比高宽,所以垂直空间是溢价。
      【解决方案4】:

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

      【讨论】: