2017-09-23 83 views
-3

我的講師對while循環,例如方法:我的講師的while循環和我的while循環之間有什麼區別嗎?

#include <stdio.h> 
int main(){ 
    int mark; 
    mark = 0; 
    while (mark !=100){ 
    printf("Please input your mark"); 
    scanf("%i",&mark); 
    if (mark <= 50){ 
     printf("You need to practice more"); 
    } 
    else if (mark==100){ 
     printf("You are too good. Nothing to say to you. Keep it up"); 
    } 
    } 
    return 0; 
} 

,這是我對while循環的方法:基於共同作用的結果

#include <stdio.h> 
int main(){ 
    int mark; 
    printf("Please input your mark"); 
    scanf("%i",&mark); 
    while (mark !=100){ 
    if (mark <= 50){ 
     printf("You need to practice more"); 
    } 
    printf("Please input your mark"); 
    scanf("%i",&mark); 

    } 
if (mark==100){ 
    printf("You are too good. Nothing to say to you. Keep it up"); 
} 

return 0; 
} 

。我看到沒有區別。但是我接受了嗎?

+1

通過手動或調試器自行完成代碼,並查看沒有有效的區別。事實上,在你的代碼中,'if'語句是不必要的;循環的唯一出路是標記== 100。 –

+8

你們倆都應該檢查scanf的返回值 –

+4

你的講師版本需要更少的陳述,所以更乾淨。然而,'do {...} while'循環甚至可以更好,因爲它不需要初始化'mark'。 –

回答

-1

你的代碼和你的演講代碼之間沒有語義上的區別,除了你只是增加了額外的if語句,這實際上使代碼更長。

+1

這不是問題 –

2

第三個選項(do ... while())。還清理了琴絃。雖然優化編譯器可能會在編譯期間添加等價的繼續,但continue可以避免冗餘比較。

#include <stdio.h> 
int main() { 
    int mark; 
    do { 
     printf("Please input your mark: "); 
     scanf("%i", &mark); 
     if (mark <= 50) { 
      printf("You need to practice more.\n"); 
      continue; /* optimizing compiler may already do this */ 
     } 
    } while (mark != 100); 
    printf("You are too good. Nothing to say to you. Keep it up.\n"); 
    return 0; 
} 
+0

我編輯你的代碼來添加檢查scanf讀取一個數字。 –

+0

當'scanf'失敗並且沒有分配發生時,代碼的當前版本需要'mark'來初始化。 –

+0

自動變量'mark'最初可以爲100.如果'scanf'失敗並且沒有對'mark'進行賦值,那麼它會得出結論''你太好了。「'但是我們正在挑剔,這是do-while循環的例子很重要。 –