把上面合为一个完整可运行的代码
时间: 2024-10-29 12:14:58 浏览: 5
当然可以,这是一个完整的C语言程序,它会从用户输入中获取两组数值,然后计算它们的协方差和相关系数:
```c
#include <stdio.h>
#include <math.h> // 引入数学库以使用sqrt函数
double calculate_mean(double arr[], int size) {
double sum = 0;
for(int i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
double calculate_std_deviation(double arr[], int size, double mean) {
double variance = 0;
for(int i = 0; i < size; i++) {
variance += pow(arr[i] - mean, 2);
}
variance /= size;
return sqrt(variance);
}
void compute_covariance_and_correlation(double x[], double y[], int n) {
double meanX = calculate_mean(x, n);
double meanY = calculate_mean(y, n);
double covar = 0;
for(int i = 0; i < n; i++) {
covar += (x[i] - meanX) * (y[i] - meanY);
}
covar /= n;
double stdDevX = calculate_std_deviation(x, n, meanX);
double stdDevY = calculate_std_deviation(y, n, meanY);
double corrcoef = covar / (stdDevX * stdDevY);
printf("协方差: %.2f\n", covar);
printf("相关系数: %.2f\n", corrcoef);
}
int main() {
int n;
printf("请输入数据的数量:");
scanf("%d", &n);
double x[n], y[n];
for(int i = 0; i < n; i++) {
printf("请输入第%d个x值和y值:", i + 1);
scanf("%lf %lf", &x[i], &y[i]);
}
compute_covariance_and_correlation(x, y, n);
return 0;
}
```
这个程序首先计算两组数据的平均值,接着计算协方差,并根据各自的平均值和标准偏差计算相关系数。请注意,这里假设用户将输入正确的数据,如果需要更完善的输入验证,可以在适当位置添加错误处理代码。
阅读全文