【发布时间】:2016-02-26 21:28:52
【问题描述】:
假设我得到了一个数字列表:8,4,5,3,2,1。
此列表的滚动平均值为:8、6、5.7、5、4.4、3.8。
我的程序使用这个算法:
新平均值 = (((旧平均值 * 第一次迭代) + 下一个数字 / (下一次迭代))。
问题是:我的程序输出所有运行平均值,除了第一个(技术上只是第一个数字,因为一个数字除以 1 就是那个数字)。它还在最后输出一个随机数。如何修复我的算法以将第一个平均值与所有其他运行平均值结合起来?旁注:在算法中,第一个“旧平均值”是第一个数字本身。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int i,n, input_cases, x;
double numbers[100]; double previous[100];
double mean[100]; double old_average[100]; double new_average[100];
double *results = malloc(input_cases*sizeof(double));
printf("Total amount of numbers: ");
if (scanf("%d", &n) != 1) { /* validates input */
fprintf (stderr, "error: invalid input.\n");
return 1;
}
for (i=0; i<n; i++){
scanf("%lf", &numbers[i]);
}
old_average[0] = numbers[0];
for (i=0; i<n; i++){
new_average[i] = (((old_average[i] * (i+1)) + numbers[i+1]) / (i+2));
old_average[i+1]=new_average[i];
printf("%lf\n", new_average[i]);
}
return 0;
}
这是我的程序使用上述示例输入/输出的内容:
Input:
8
4
5
3
2
1
Output:
6.0 (This is the SECOND running average, not the first)
5.666667
5.000000
4.400000
3.830000
3.2857514 (This is the random number that doesn't belong)
【问题讨论】:
-
尝试打印 old_average 而不是 new_average...
标签: c moving-average