【问题标题】:Changing a for loop to a while loop doesn't work correctly (simple code)将 for 循环更改为 while 循环无法正常工作(简单代码)
【发布时间】:2016-11-02 19:57:06
【问题描述】:

我想要这个输出:

Insert a integer: 13
13
14
16
17
19

使用for 循环,它可以正常工作:

for( ; ; num++)
{
    if (num%3==0)
        continue;
    else
        if(num%10==0)
            break;

    printf("%d\n", num);
}

但是当我尝试更改为 while 循环时:

while(1)
{
    if (num%3==0)
        continue;
    else
        if(num%10==0)
            break;

    printf("%d\n", num);
    num++;
}

奇怪的事情发生了:

Insert a integer: 13
13
14

你们能帮帮我吗?

【问题讨论】:

  • while 循环中,numnum % 3 == 0 为真的循环迭代中不会增加。 continue不会跳到while 块中的最后一条语句。 for 循环版本总是 在每次迭代时递增 num,因为这是处理 for 循环中的第三个表达式的方式。

标签: c loops for-loop while-loop


【解决方案1】:

使用下面的代码

Do
{    
    if (num%3==0)
        continue;
    else
        if(num%10==0)
            break;

    printf("%d\n", num);
   }while(num++);

【讨论】:

  • 谢谢你,Twinkle。
  • 很遗憾没有,因为我需要的第一个数字就是插入的数字。
  • ++numnum++ 的更改并没有真正影响任何事情。当然,您可以转换为 do { … } while (num++); 循环。
【解决方案2】:

在代码开头添加num++ 行(while 循环)。 当循环到达num%3==0 时,它会不断重复。

num--;

while(1)
{
    num++;
    if (num%3==0)
        continue;
    else
        if(num%10==0)
            break;

    printf("%d\n", num);
}

【讨论】:

  • 如果 num 初始递增,将跳过输入的数字。 Ricardo 也希望对其进行处理。
  • 你总是可以从 num-1 开始
【解决方案3】:

for 更改为while 循环时应添加num++

while(1)
{
    if (num%3==0) {
        num++; /* <- add this */

        continue;
    }
    else
        if(num%10==0)
            break;

    printf("%d\n", num);
    num++;
}

两个增量 一个循环中的num++看起来很丑,所以你可能想要重新设计循环到

while (num % 10 != 0) {
  if (num % 3 != 0) 
    printf("%d\n", num);

  num++;
}

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多