我需要在C中编写一个程序来读取用户输入的整数,在输入0时停止,然后找到它们的平均值。
这就是我目前的
int main(void) {
int total, h = -1, sum2 = 0;
float mean;
printf("\nYou've chosen Average.\nEnter the numbers you want to find the average of with a 0 at the end (eg. 2 1 5 12 0)\n");
scanf(" %d", &total);
while (total > 0) {
h++;
sum2 += total;
scanf (" %d\n", &mean);
mean = (float)total / h;
}
printf("Average = %.2f\n", mean);
return 0;
}
任何帮助将不胜感激
更新
int main(void) {
int total, h = 0;
float mean;
printf("\nYou've chosen Average.\nEnter the numbers you want to find the average of with a 0 at the end (eg. 2 1 5 12 0)\n");
while (scanf (" %d", &total) == 1 && total > 0) {
h++;
sum2 += total;
}
mean = (float)total / h;
printf("Average = %.2f\n", mean);
return 0;
}
答案 0 :(得分:1)
基本上你想要的是 cumulative moving average ;您可以使用每个新输入值更新平均值。
在伪代码中,它看起来像
cma = 0; // mean is initially 0
n = 0; // n is number of inputs read so far
while nextValue is not 0
cma = (nextValue + (n * cma )) / (n + 1)
n = n + 1
end while
让我们看看它如何与1, 2, 3, 4, 5, 0
:
cma = 0;
n = 0
nextValue = 1
cma = (1 + (0 * 0))/(0 + 1) == 1/1 == 1
n = 1
nextValue = 2
cma = (2 + (1 * 1))/(1 + 1) == 3/2 == 1.5 // (1 + 2)/2 == 1.5
n = 2
nextValue = 3
cma = (3 + (2 * 1.5))/(2 + 1) == 6/3 == 2 // (1 + 2 + 3)/3 == 2
n = 3
nextValue = 4
cma = (4 + (3 * 2))/(3 + 1) == 10/4 == 2.5 // (1 + 2 + 3 + 4)/4 == 2.5
n = 4
nextValue = 5
cma = (5 + (4 * 2.5))/(4 + 1) == 15/5 == 3 // (1 + 2 + 3 + 4 + 5)/5 == 3
n = 5
nextValue = 0
您应该能够非常轻松地将该伪代码转换为C.请记住,整数除法给出整数结果 - 1/2
将产生0
,而不是0.5
。至少有一个操作数必须是浮点类型才能获得浮点结果。您可能希望使用double
作为输入和结果。