繁体   English   中英

C中的无限While循环

[英]Infinite While Loop In C

这段代码创建了一个无限循环,我想按照一些步骤将数字首次显示为0并打印该程序需要花费多少步骤

    int debut,i;
    printf("de (>= 1) ? ");
    do
    {            
        scanf("%d",&debut);
    } 
    while (debut < 1);

    int fin;
    printf("a >=  <<  << ) ? ");
    do 
    {            
        scanf("%d",&fin) ;
    } 
    while (fin < debut);

   for (;debut<=fin;debut++){
       i=0;
       while(debut!=0)
       {
           if(debut%3==0)
           {
               debut+=4;
           }
           else if (debut%3!=0 && debut%4==0){
               debut/=2;
           }
           else if (debut%3!=0 && debut%4!=0)
           {
               debut-=1;
           }
           i+=1;

       }
       printf("%d\n->%d",debut,i);    
       }
for(debut<=fin;debut++) {
    while(debut!=0) {
        //do stuff
    }
    //debut == 0, debut <= fin
}

好的,大量编辑我的答案。 我看错了循环。

为了进入for循环, debut必须是<=fin 每当fin >0且进入for循环时,您就会陷入for循环中。

您陷入了while循环中,直到除非debut == 0返回true为止。 只要debut++ <= fin ,您就会陷入for循环中。 您正在while循环中修改debut ,但是fin保持不变。 因此, while循环将debut减少为0 ,并且for循环每次都会进入下一个迭代。

简短的回答 :我怀疑您打算将while循环用于debut副本 ,而不是debut


  • 让我们假设debut == 3fin == 5
  • 我们执行for循环的第一次迭代,其中涉及while循环的完整演练。
  • 在while循环之后,我们debut == 0fin == 5i == 12
  • 然后,我们打印一些信息。
  • 但是,我们现在将再次遍历for循环。 由于我们所做的工作, debut已减少为0 ,因此,每次运行此代码时,在for循环迭代结束时,我们将拥有一个debut == 0 ,这将导致for循环永不退出。

在代码中内联显示可能会更有用...

for (;debut<=fin;debut++){
    // Let's assume we get here. We can assume some sane debut and fin values,
    // such as the 3 and 5 suggested above.

    int i=0;
    while (debut != 0) {
        // Stuff happens that makes debut go to zero.
    }

    // To get to this point, we __know__ that debut == 0.
    // We know this because that's the condition in the while loop.

    // Therefore, when we do the comparison in the for loop above for the
    // next iteration, it will succeed over and over again, because debut
    // has been changed to zero.

    printf("%d->%d\n",debut,i);
}

就我个人而言,我怀疑您正在寻找一组数字的迭代次数。 对我来说,这听起来像是使用功能的理想之地。 我建议的代码看起来像这样。

#include <stdio.h>

int iterations(int debut) {
    int i = 0;

    while(debut!=0)
    {
        if(debut%3==0)
        {
            debut+=4;
        }
        else if (debut%3!=0 && debut%4==0){
            debut/=2;
        }
        else if (debut%3!=0 && debut%4!=0)
        {
            debut-=1;
        }

        i+=1;
    }

    return i;
}

int main() {
    int debut = 3;
    int fin = 5;

    for (;debut<=fin;debut++) {
        printf("%d -> %d\n", debut, iterations(debut));
    }
}

另外,仅出于注意的目的,请注意,在最后给出的示例代码中,我删除了所有输入的scanf代码。 它与您的实际问题无关,它减少了任何人都需要扫描才能了解问题所在的代码总数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM