CCF 202206-1 归一化处理 (C++)
作者:互联网
难点在于求方差的时候不能进行先求和再平均,否则会爆掉
可以采用 compute 函数所实现的方法
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int n;
int a[1005];
int sum = 0;
// 平均值
double avg;
double compute(double oldAvg, double newA, double m){
// oldAvg 指前面 m-1 个数的平均值, newA 是第 m 个数
// 计算并返回加上 前面 m 个数的平均值
double newAvg;
newAvg = oldAvg/m*(m-1)+newA/m;
return newAvg;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
sum += a[i];
}
avg = (double)sum/(double)n;
double Da = 0;
for (int i = 0; i < n; i++){
Da = compute(Da, ((double)a[i]-avg)*((double)a[i]-avg), (double)(i+1));
}
double sqrtDa = sqrt(Da);
for (int i = 0; i < n; i++){
printf("%.16f\n", (a[i]-avg)/sqrtDa);
}
return 0;
}
标签:202206,avg,int,double,sum,Da,++,归一化,CCF 来源: https://www.cnblogs.com/understanding-friends/p/16529593.html