I have the following code and every time i run it, I get an extra count. Say for example that I input 8 first round and then a 2 next round and exit with the sentinel -1, the sum will be 10 as expected, but the count will be 3. I’ve debugged the program and no matter if count comes before the scanf() or after, I still get a 3 value. One possible solution is to initialized count to -1. However, I feel I shouldn’t have to and setting count equal to zero should work. Do I have to set count to -1?
#include <stdio.h>
void calculateAverage()
{
int grade = 0, count, sum = 0;
double average;
count = 0;
while(grade != -1)
{
sum += grade;
count++;
printf("input a grade: n");
scanf("%d", &grade);
}
average = (double)(sum)/(double)(count);
printf("%.2lf", average);
return;
}
int main( )
{
while (1)
calculateAverage();
return 0;
}
2
Answers
You are incrementing count just before you enter -1. So, it counts -1 as well. Just in increase is if it’s not -1.
For starters there is no great sense to declare the variable
sum
as having the typeint
because in any case you are casting it to the typedouble
You are increasing the variable
count
before the user will enter something.The function can be defined the following way as it is shown in the demonstrative program below.
The program output might look like