Bisus

Untitled

Oct 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <time.h>
  4. int f(const char *name, double *d);
  5.  
  6. /* Ф-ия, получающая имя файла с вещественной последовательностью неизвестной длины.
  7.  * Она записывает по адресу d среднее квадратическое отклонения чисел этого файла от их среднего арифметического.
  8.  * Возвращает:
  9.  * длину последовательности, в случае успешного завершения;
  10.  * -1, если не удалось открыть файл;
  11.  * -2, если не удалось прочитать элемент.
  12.  * */
  13. int f(const char *name, double *d)
  14. {
  15.     FILE *input;
  16.     double x, arith = 0, arith_of_squares = 0;
  17.     int n = 0;
  18.  
  19.     if( !(input = fopen(name, "r")) )
  20.         return -1;
  21.     // Файл открыт
  22.  
  23.     while( fscanf(input, "%lf", &x)==1 )
  24.     {
  25.         arith += x;
  26.         arith_of_squares += x*x;
  27.         n++;
  28.     }
  29.     if( !feof(input) )
  30.     {
  31.         fclose(input);
  32.         return -2;
  33.     }
  34.     *d = sqrt(arith_of_squares/n - arith*arith/(n*n));
  35.     return n;
  36. }
  37.  
  38. int main(int argc, const char *argv[])
  39. {
  40.     double d;
  41.     clock_t begin_time, end_time;
  42.  
  43.     if(argc!=2)
  44.     {
  45.         fprintf(stderr, "Usage: %s name_of_file\n", argv[0]);
  46.         return -1;
  47.     }
  48.  
  49.     begin_time = clock();
  50.     printf("f(%s, &d) returned %d\n", argv[1], f(argv[1], &d));
  51.     end_time = clock();
  52.     printf("d==%.16lf\ntime==%lf\n", d, (double)(end_time - begin_time)/CLOCKS_PER_SEC);
  53.  
  54.     return 0;
  55. }
Add Comment
Please, Sign In to add comment