#13170. 珅泽教育CSP-J第一轮模拟考第三十套 第 27 题

珅泽教育CSP-J第一轮模拟考第三十套 第 27 题

二、程序阅读题(每个小题单独作答,共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;
}

输入3个点 (-1,10),(1,5),(3,1.5) 时,a,b 的符号是( )。

{{ select(1) }}

  • a>0,b<0
  • a>0,b>0
  • a<0,b<0
  • a<0,b>0