难点在于求方差的时候不能进行先求和再平均,否则会爆掉
可以采用 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; }