根据预测明年的平均工资这段代码int next_year = sample_data[sample_size - 1].year + 1; float next_salary = a * next_year + b; printf("The predicted average salary for %d is %.2f\n", next_year, next_salary);写出一个可以查看任一年的平均工资
时间: 2023-12-14 15:35:38 浏览: 61
salary-prediction:预测薪水
可以根据上面的代码稍加修改,让用户输入任意想要查询的年份,然后输出该年份的预测平均工资。具体代码如下:
```c
#include <stdio.h>
#define MAX_SIZE 100
struct salary_data {
int year;
float salary;
};
int main() {
int sample_size, query_year;
float a, b;
struct salary_data sample_data[MAX_SIZE];
// 读入样本数据
printf("Please enter the number of years for which you have salary data: ");
scanf("%d", &sample_size);
printf("Please enter the salary data:\n");
for (int i = 0; i < sample_size; ++i) {
scanf("%d %f", &sample_data[i].year, &sample_data[i].salary);
}
// 计算线性回归系数
float x_sum = 0, y_sum = 0, xy_sum = 0, x2_sum = 0;
for (int i = 0; i < sample_size; ++i) {
float x = sample_data[i].year, y = sample_data[i].salary;
x_sum += x;
y_sum += y;
xy_sum += x * y;
x2_sum += x * x;
}
a = (sample_size * xy_sum - x_sum * y_sum) / (sample_size * x2_sum - x_sum * x_sum);
b = (y_sum - a * x_sum) / sample_size;
// 查询任意年份的预测平均工资
printf("Please enter the year for which you want to predict the average salary: ");
scanf("%d", &query_year);
float predicted_salary = a * query_year + b;
printf("The predicted average salary for %d is %.2f\n", query_year, predicted_salary);
return 0;
}
```
这个程序可以读入任意数量的样本数据,并且计算出对应的线性回归系数。用户可以输入任意想要查询的年份,然后程序会输出该年份的预测平均工资。
阅读全文