【发布时间】:2015-05-25 15:06:40
【问题描述】:
大家好,我有一个 c 编程作业,上面写着:
" 编写一个输入整数测试分数列表的 C 程序 介于 0 和 100 之间,并计算最高分、最低分 分,以及平均分。使用 -1 作为哨兵,标记结束 输入。拒绝任何超出 0 到 100 范围的测试分数。你的程序 还应该检测并拒绝错误的输入,例如字母和字符。 您应该有一个读取和验证输入测试分数的函数 并拒绝无效和错误的输入。这是一个示例运行“
我写了一个代码,但我的问题是如何拒绝像字符这样的输入..:
#include <stdio.h>
#define sentinel -1 // to end the program
int main ()
{
int status, score, sum, i, max, min;
double avrg;
i = 0; /* the counter */
sum = 0; // the total scores
printf (" Enter the score , %d to termenate > ", sentinel);
status = scanf ("%d", &score); // checking the validity of the input
max = score; // the initial maximum
min = score; // the initial minimum
while (score != sentinel) {
while (score < 0 || score > 100) // no negative or more than 100 score
{
printf ("The number is out of the range ; try again> ");
scanf ("%d", &score);
}
sum = sum + score;
i = i + 1;
printf (" Enter the score , %d to termenate > ", sentinel);
status = scanf ("%d", &score);
if (score > max && score < 100)
max = score;
if (score < min && score > 0)
min = score;
}
if (i != 0) {
avrg = (double) sum / i; // the sum of scores over the number of scores
printf (" The avarage is : \n %.2f ", avrg);
printf ("\n");
printf (" Maximum score is : \n %d", max);
printf ("\n");
printf ("Minmum score is : \n %d", min);
} else // when the user ends the program without entering any value
{
printf ("You didn't enter any score");
}
return 0;
}
希望你能帮到我
【问题讨论】:
-
请用正确的缩进格式化代码。您没有检查每个值
-
scanf和%d如果输入了无效的输入(如字符),则返回 0。因此,如果status为 0,则scanf失败。因此,您必须清除stdin并再次提示用户,直到输入有效的输入。