You'll have to maintain a counter to do what you're trying to do. its just int counter = 0;
and in the loop: counter++
int counter = 0;
while (user_input != -1)
{
total += user_input;
counter ++;
scanf ("%d", &user_input);
}
average = total / counter;
printf("Average = %f\n", average);
obviously, you'll have to check if scanf()
returned atleast 1
--- EDIT ---
the following program(that corresponds to the previous program) is VALID and works as required. People who do not understand how scanf()
works, should stay the damn out:
#include <stdio.h>
int main(int argc, char *argv[])
{
int total = 0;
float average = 0.0f;
int userinput = 0;
int counter = -1;
while(userinput != -1){
counter ++;
if(scanf("%d",&userinput) == 1 && userinput != -1){
total += userinput;
}
}
average = ((float)total/(float)counter);
printf("Average = %f", average);
return 0;
}
Input: 10 20 30 40 50 60 -1
Output: Average = 35