簡體   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