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()'からの復帰を扱う、または以外の場合は、問題があるでしょうべきで続い*他*変数にそれを読んで、それを最初に確認してください... –
数字(または空白)が入力されます。 – Dmitri