编写函数:double variance(double data[], int n); 计算数组中n个元素的方差,并用主函数测试之。
时间: 2023-07-15 07:13:25 浏览: 76
variance:计算方差
以下是实现方差计算的函数和主函数:
```c++
#include <iostream>
using namespace std;
double variance(double data[], int n) {
double sum = 0;
double mean = 0;
double variance = 0;
// 计算平均值
for (int i = 0; i < n; i++) {
sum += data[i];
}
mean = sum / n;
// 计算方差
for (int i = 0; i < n; i++) {
variance += (data[i] - mean) * (data[i] - mean);
}
variance /= n;
return variance;
}
int main() {
double data[] = { 1, 2, 3, 4, 5 };
int n = 5;
double result = variance(data, n);
cout << "方差为:" << result << endl;
return 0;
}
```
输出:
```
方差为:2
```
阅读全文