#13166. 珅泽教育CSP-J第一轮模拟考第三十套 第 23 题
珅泽教育CSP-J第一轮模拟考第三十套 第 23 题
二、程序阅读题(每个小题单独作答,共40分)
程序阅读(2):最小二乘法
程序拟合直线 y=ax+b。
#include <bits/stdc++.h>
using namespace std;
int NUM_SAMPLES;
void least_squares(double x[], double y[], double& a, double& b) {
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x_squared = 0;
for (int i = 1; i <= NUM_SAMPLES; i++) {
sum_x += x[i];
sum_y += y[i];
sum_xy += x[i] * y[i];
sum_x_squared += x[i] * x[i];
}
double denominator = NUM_SAMPLES * sum_x_squared - sum_x * sum_x;
a = (NUM_SAMPLES * sum_xy - sum_x * sum_y) / denominator;
b = (sum_x_squared * sum_y - sum_x * sum_xy) / denominator;
}
int main() {
double x[105], y[105], a, b;
scanf("%d", &NUM_SAMPLES);
for(int i = 1; i <= NUM_SAMPLES; i++)
scanf("%lf %lf", &x[i], &y[i]);
least_squares(x, y, a, b);
printf("a = %.1lf, b = %.1lf\n", a, b);
return 0;
}
程序第4行参数中的 & 是取地址运算符。( )
{{ select(1) }}
- 正确
- 错误