将 for 循环更改为 while 循环无法正常工作(简单代码)

标签 c loops for-loop while-loop

我想要这个输出:

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

请大家帮帮我好吗?

最佳答案

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++;
}

关于将 for 循环更改为 while 循环无法正常工作(简单代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127886/

相关文章:

c++ - 根据条件替换指令

c - 具有相同参数类型的结构中的函数指针

c - 该位运算符代码是副作用(K&R C 书中使用的术语)还是依赖于机器的处理指令?

performance - 在 Lua 中,我应该在循环的每次迭代中还是在循环之前定义一个变量?

c - C语言中如何结束循环?

r - 带for循环的数据汇总

c - 从文件扫描时如何使用结构实现堆栈

mysql - 夹板和 MySQL : Null storage passed as non-null param

javascript - 如果包含键值对,则返回数组中的对象

java - 在java中搜索没有循环的arraylist