【问题标题】:Error Check for scanf using while loops?使用while循环对scanf进行错误检查?
【发布时间】:2016-08-09 00:38:18
【问题描述】:

我一直在尝试对我的程序进行错误检查,scanf 使用 while 循环,但我不确定如何执行此操作。

我想确保用户输入的评委人数在 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);
}

【问题讨论】:

    标签: c while-loop scanf error-checking


    【解决方案1】:

    您只需要在要检查的区域周围使用 do-while 循环。如果不满足条件(在while部分),循环将重复并再次提示用户。

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

    【讨论】:

      【解决方案2】:

      尝试以下方法:

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

      【讨论】:

      • 很高兴知道它有帮助,选择它作为接受答案:) 谢谢
      • 嘿,我只是想知道puts有什么用?我是 c 新手,正在努力学习 :) 谢谢。
      • @Bronson puts 打印它的字符串参数和一个新行,所以puts("foo");printf("foo\n"); 相同
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多