Reputation:
I'm trying to tell the user to insert numbers as many as they can, and insert -1 if they want to terminate. The program is working good, but I tried to enter -1 as a first number and I got this output : -nan
This is the code :
main()
{
int counter = 0;
float grade;
float total = 0;
float average;
printf("Compute the average grades.\n");
printf("Grade = -1 will terminate the process\n");
printf( "Enter grade (-1 to terminate): " );
scanf("%f",&grade);
while(grade != -1)
{
counter++;
total+=grade;
printf( "Enter grade (-1 to terminate): " );
scanf("%f",&grade);
}
average = total / counter;
printf("Class average is %.2f\n", average);
}
Upvotes: 0
Views: 76
Reputation: 26703
The problem is
average = total / counter;
when counter
is 0, which it is when you never iterate the loop body even once.
Wrap that line (and maybe the following output) into a
if(counter>0)
{
//...
}
with a following
else
{
//...
}
You can output something like
"No numbers, no average. ;-)".
Upvotes: 1