Advertisement
agul

20121025_mm_msu_practice

Oct 25th, 2012
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. double getDeviation(FILE * in) {
  5.     int n = 0;                                                      // n - количество чисел 
  6.     double ans = 0, squaresSum = 0, sum = 0, mediane = 0, current;  // ans - ответ
  7.                                                                     // squaresSum - сумма квадратов (x_1^2 + x_2^2 + ... + x_n^2)
  8.                                                                     // sum - сумма (x_1 + x_2 + ... + x_n)
  9.                                                                     // mediane - среднее арифметическое = sum / n
  10.                                                                     // current - текущее число
  11.     while (fscanf(in, "%lf", &current) == 1) {
  12.         ++n;
  13.         squaresSum += current * current;
  14.         sum += current;
  15.     }
  16.     if (!n) {                                                       // if (n == 0)
  17.         fprintf(stderr, "Incorrect file formed\n");
  18.         exit(-1);
  19.     }
  20.     mediane = sum / n;
  21.     ans = (squaresSum - 2 * sum * mediane + mediane * mediane * n) / n;
  22.     return ans;
  23. }
  24.  
  25. int main(void) {
  26.     FILE * in = fopen("input.txt", "r");
  27.     if (!in) {
  28.         perror("Cannot open input file");
  29.         return -1;
  30.     }
  31.     double ans = getDeviation(in);
  32.     fclose(in);
  33.     FILE * out = fopen("output.txt", "w");
  34.     if (!out) {
  35.         perror("Cannot open output file");
  36.         return -1;
  37.     }
  38.     fprintf(out, "%.16lf\n", ans);
  39.     fclose(out);
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement