简体   繁体   中英

Error Check for scanf using while loops?

I've been trying to do an error check for my program, for scanf using a while loop, but I am unsure of how to do this.

I want to make sure the user inputs between 4 and 8 for number of judges, and the score doesn't go below 0 or above 10.

could someone please help me out?

Thanks!

#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);
}

You just need to use do-while loops around the areas that you are checking. If the condition (in the while part) is not met, the loop will repeat and the user will be prompted again.

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

Try the following:

// 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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