计算方差scalar c++
时间: 2024-05-13 11:14:34 浏览: 50
以下是计算方差的C++代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
double calculate_mean(double arr[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum / n;
}
double calculate_variance(double arr[], int n) {
double mean = calculate_mean(arr, n);
double sum = 0;
for (int i = 0; i < n; i++) {
sum += pow(arr[i] - mean, 2);
}
return sum / n;
}
int main() {
double arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
double variance = calculate_variance(arr, n);
cout << "The variance of the array is: " << variance << endl;
return 0;
}
```
在上面的代码中,`calculate_mean`函数用于计算数组的平均值,`calculate_variance`函数用于计算方差。程序首先定义了一个数组,然后计算数组的方差,并将结果打印到控制台上。
阅读全文