2015-12-02 248 views
0

不同的輸出據我所知for環和while循環之間的差別看起來是這樣的:WHILE循環顯示出比FOR循環

爲:

拳頭初始化時則條件表達式檢查如果結果爲TRUE那麼只有語句部分得到執行,這個循環是連續的,直到條件表達式結果爲FALSE

當:

條件表達式首先檢查,如果結果TRUE然後聲明部分被執行,否則不,這個循環是連續的,直到條件表達式的結果FALSE


今天,我寫了檢查,如果string有重複的算法,如果是隻打印那些沒有:

#include<stdio.h> 
#include<string.h> 

int main(void){ 
    const char *str = "Mississippi"; 
    char tmp[15] = {0}; 
    size_t i=0,j=0,k=1; 
    int found=0; 

    tmp[0] = str[0]; 

    printf("Before = %s\n",str); 
    while(str[i] != '\0'){ 
     for(j=0;tmp[j] != '\0';j++){ 
      if(tmp[j] == str[i]){ 
       found++; 
      } 
     } 

     if(found==0){ 
      tmp[k]=str[i]; 
      k++; 
     } 

     found=0; 
     i++; 
    } 

    tmp[strlen(tmp)] = '\0'; 
    printf("After = %s\n",tmp); 
    return 0; 
} 

輸出:

Before = Mississippi 
After = Misp 

現在看如果替換for循環會發生什麼情況:

for(j=0;tmp[j] != '\0';j++){ 
    if(tmp[j] == str[i]){ 
     found++; 
    } 
} 

以`while循環:

while(tmp[j] != '\0'){ 
    if(tmp[j] == str[i]){ 
     found++; 
    } 
    j++; 
} 

我得到:

#include<stdio.h> 
#include<string.h> 

int main(void){ 
    const char *str = "Mississippi"; 
    char tmp[15] = {0}; 
    size_t i=0,j=0,k=1; 
    int found=0; 

    tmp[0] = str[0]; 

    printf("Before = %s\n",str); 
    while(str[i] != '\0'){ 
     while(tmp[j] != '\0'){ 
      if(tmp[j] == str[i]){ 
       found++; 
      } 
      j++; 
     } 

     if(found==0){ 
      tmp[k]=str[i]; 
      k++; 
     } 

     found=0; 
     i++; 
    } 

    tmp[strlen(tmp)] = '\0'; 
    printf("After = %s\n",tmp); 
    return 0; 
} 

但產量並不如預期:

Before = Mississippi 
After = Misp 

但是:

Before = Mississippi 
After = Misisipi 

爲什麼會發生這種情況?

+2

TLDR;請提供一個簡短而親切的[MCVE](http://stackoverflow.com/help/mcve)來說明問題。不要發佈有效的代碼。 –

+0

@WeatherVane對不起,用示例去掉了部件。 – Michi

+0

Down Voter請解釋一下,爲什麼?有沒有機會看到誰投下了我的票? – Michi

回答

2

現在缺少的是,for環路初始化j爲0時,它首先進入。

雖然j被初始化爲0,當它宣佈,將while循環另一個while循環中調用,所以它不會每次都重新初始化。

添加初始化:

j=0; 
    while(tmp[j] != '\0'){ 
     if(tmp[j] == str[i]){ 
      found++; 
     } 
     j++; 
    } 

,你會得到:

Before = Mississippi 
After = Misp 
+0

哦,我很傻。謝謝。 – Michi

1

因爲while循環在最外while循環的每次迭代中不初始化j=0

1

請注意,while循環不會初始化j0

刪除的j的初始化0並在嵌套循環while前面加

j = 0; 

1

您不會使用while循環將j重置爲0。

該位:

for(j=0; 
1

for loop

for (init-statement(optional) ; condition(optional) ; 
     iteration_expression(optional)) 
    statement 

上述語法生成的代碼等同於:

{ 
    init_statement 
    while (condition) { 
    statement 
    iteration_expression ; 
    } 
} 

除了由init聲明宣稱

  1. 名稱(如果初始化語句是一個聲明)和條件聲明的名稱(如果條件是 聲明)是在相同的範圍(這是聲明的範圍也是 )。
  2. 的語句將執行iteration_expression
  3. 空狀態continue相當於while(true)