原理:
data(1) = data(1)
data(2) = (data(1) + data(2))/2
data(3) = (data(1) + data(2) + data(3))/3
data(N) = (data(1) + ... + data(N))/N
运行效果:
代码:
void Smooth(float data[], int N, int size)//N为平均数(范围1-size),size为数组大小
{
float Sum = 0;
int nSize = 0;
for (int k = 0; k < size; k++) //空白数据不计算
{
if (data[k] == 0)
break;
nSize++;
}
//为了方便处理空白数据,是从数组最后往前计算覆盖
for (int j = nSize-1; j >0; j--) //数组首位和末位数值不计算
{
if (j > N) //多于平均数的按N个的数值和算平均
{
for (int i = N; i > 0; i--)
Sum += data[j - i];
data[j - 1] = Sum / N;
}
else //少于平均数的按实际个数的数值和算均值
{
for (int i = j; i > 0; i--)
Sum += data[j - i];
data[j - 1] = Sum / j;
}
Sum = 0;
}
}
int main()
{
float data[10] = {6,10.2,10.3,4,9,10.5,11.0,11,0,0 };
for (int i = 0; i < 10; i++)
printf("%.2f ", data[i]);
printf("\n");
Smooth(&data[0], 8, 10);
for (int i = 0; i < 10; i++)
printf("%.2f ", data[i]);
}