7:使用指针,求10个数均方差。
时间: 2023-06-11 22:10:37 浏览: 153
假设这10个数存储在一个数组中,我们可以先计算它们的均值,然后再计算每个数与均值的差的平方和,最后除以10即可得到均方差。
以下是使用指针实现的代码:
```c
#include <stdio.h>
#include <math.h>
double mean(double *nums, int size) {
double sum = 0;
for (int i = 0; i < size; i++) {
sum += nums[i];
}
return sum / size;
}
double variance(double *nums, int size) {
double avg = mean(nums, size);
double sum = 0;
for (int i = 0; i < size; i++) {
double diff = nums[i] - avg;
sum += diff * diff;
}
return sum / size;
}
int main() {
double nums[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double result = variance(nums, 10);
printf("The variance is: %f\n", result);
return 0;
}
```
输出结果为:
```
The variance is: 8.250000
```
阅读全文