fork download
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. // Given data
  5. int x[] = {-2, -1, 0, 1, 2};
  6. int y[] = {1, 2, 3, 4, 5};
  7. int n = 5; // Number of data points
  8.  
  9. // Variables to calculate sums
  10. int sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0;
  11.  
  12. // Calculate sums
  13. for (int i = 0; i < n; i++) {
  14. sum_x += x[i];
  15. sum_y += y[i];
  16. sum_xy += x[i] * y[i];
  17. sum_x2 += x[i] * x[i];
  18. }
  19.  
  20. // Calculate slope (b) and intercept (a)
  21. float b = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x);
  22. float a = (sum_y - b * sum_x) / n;
  23.  
  24. // Output the results
  25. printf("Least square line: y = %.2f + %.2fx\n", a, b);
  26.  
  27. return 0;
  28. }
  29.  
  30.  
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Least square line: y = 3.00 + 1.00x