我必须在 C++ 中实现标准差和方差。
#include <iostream>
#include <string>
#include <math.h>
class StdDeviation
{
private:
int max;
double value[100];
double mean;
public:
double CalculateMean()
{
double sum = 0;
for(int i = 0; i < max; i++)
sum += value[i]; // Question 1. at bottom.
return (sum / max);
}
double CalculateVariane()
{
mean = CalculateMean();
double temp = 0;
for(int i = 0; i < max; i++)
{
temp += (value[i] - mean) * (value[i] - mean) ;
}
return temp / max;
}
double CalculateSampleVariane()
{
mean = CalculateMean();
double temp = 0;
for(int i = 0; i < max; i++)
{
temp += (value[i] - mean) * (value[i] - mean) ;
}
return temp / (max - 1);
}
int SetValues(double *p, int count)
{
if(count > 100)
return -1;
max = count;
for(int i = 0; i < count; i++)
value[i] = p[i];
return 0;
}
double GetStandardDeviation()
{
return sqrt(CalculateVariane());
}
double GetSampleStandardDeviation()
{
return sqrt(CalculateSampleVariane());
}
};
以下是我的问题:
- 如何确保 double 的值不会溢出并返回零。
- 如何检查我没有超过总和的最大值,即最大值的两倍?