2016-04-17 122 views
2

我一直在嘗試爲我的程序做一個錯誤檢查,對於使用while循環的scanf,但我不確定如何執行此操作。錯誤使用while循環檢查scanf?

我想,以確保法官的數量4和8之間的用戶輸入,比分不低於0或高於10

可能有人請幫助我嗎?

謝謝!

#include <stdio.h> 

int i,j,k, judges; 
float max, min,total; 

int main(){ 
    max = 0.0; 
    min = 10.0; 
    judges = 0; 
    total = 0; 

printf("Enter number of judges between 4-8: "); 
scanf("%d", &judges); 

    float scores[judges]; 

for(i = 0; i < judges; i++){ 
    printf("Enter a score for judge %d : ", i + 1); 
    scanf("%5f", &scores[i]); 
} 
for(j = 0; j < judges; j++){ 
    if(min > scores[j]){ 
     min = scores[j]; 
    } 
    if (max < scores[j]){ 
     max = scores[j]; 
    } 
} 
for(k = 0; k < judges; k++){ 
    total = total + scores[k]; 
} 
total = total-max-min; 
printf("max = %4.1f min = %4.1f total = total = %4.1f", min, max,total); 
} 

回答

0

嘗試以下操作:

// for judge 
while (1) { 
    printf("Enter number of judges between 4-8: "); 
    scanf("%d", &judges); 
    if (judges >= 4 && judges <= 8) 
     break; 
    else 
     puts("Judge out of range of 4 and 8."); 
} 

// for socres 
for(i = 0; i < judges; i++){ 
    while (1) { 
     printf("Enter a score for judge %d : ", i + 1); 
     scanf("%5f", &scores[i]); 
     if (scores[i] >= 0.0 && scores[I] <= 10.0) 
      break; 
     else 
      puts("score out of range of 0.0 and 10.0"); 
} 
+0

非常感謝您! – Bronson

+0

很高興知道它有幫助,選擇它作爲接受答案:)謝謝 – fluter

+0

嘿,我只是想知道什麼是使用puts是什麼?林新到C和試圖學習:)謝謝。 – Bronson

0

您只需要在您正在檢查的區域周圍使用do-while循環。如果條件(在while部分)不滿足,則循環將重複,並且將再次提示用戶。

do{ 
    printf("Enter number of judges between 4-8: "); 
    scanf("%d", &judges); 
}while(judges < 4 || judges > 8);