【发布时间】:2017-06-12 02:18:15
【问题描述】:
我试图通过在 while 循环中使用 if 语句来防止用户在这个简单的 C 程序中输入错误的值。但问题是,每当用户输入错误的值时,它就会存储在变量中,然后将相同的值用于进一步的计算。 这是实际的程序:
#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks\nEnter again: ");
scanf("%d", &marks);
}
total = total+marks;
a++;
}
average = total/(float)noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
【问题讨论】:
-
然后将其读入另一个变量并先检查...
-
您还应该检查并处理来自
scanf()的返回,否则如果输入的不是数字(或空格),您将遇到问题。
标签: c if-statement scanf