用C语言编写函数:double variance(double data[], int n); 计算数组中n个元素的方差,并用主函数测试之
时间: 2023-11-22 20:55:33 浏览: 69
方差计算.c
下面是用C语言编写的计算数组方差的函数和主函数:
```c
#include <stdio.h>
double variance(double data[], int n) {
double mean = 0.0, sum = 0.0, var = 0.0;
int i;
for (i = 0; i < n; i++) {
mean += data[i];
}
mean /= n;
for (i = 0; i < n; i++) {
sum += (data[i] - mean) * (data[i] - mean);
}
var = sum / n;
return var;
}
int main() {
double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
int n = sizeof(data) / sizeof(double);
printf("data: ");
for (int i = 0; i < n; i++) {
printf("%g ", data[i]);
}
printf("\nvariance: %g\n", variance(data, n));
return 0;
}
```
运行结果:
```
data: 1 2 3 4 5
variance: 2.5
```
阅读全文