你必须维护一个计数器来做你想做的事情。它只是int counter = 0;
在循环中:counter++
int counter = 0;
while (user_input != -1)
{
total += user_input;
counter ++;
scanf ("%d", &user_input);
}
average = total / counter;
printf("Average = %f\n", average);
显然,您必须检查是否scanf()
至少返回 1
--- 编辑 --- 以下程序(对应于前一个程序)是有效的并按要求工作。不了解如何scanf()
工作的人应该远离该死的:
#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;
}
输入:10 20 30 40 50 60 -1
输出:Average = 35