Advertisement
Bisus

Untitled

Nov 12th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void f(unsigned int n, double *array);
  4.  
  5. /* Предполагается, что по указателю array выделена память под n элементов.
  6.  * Ф-ия переставляет все четные элементы в началоб нечетные - в конец, без изменения порядка.
  7.  * */
  8. void f(unsigned int n, double *array)
  9. {
  10.     unsigned int i, j;
  11.     double buffer;
  12.  
  13.     for( i = 0; i<(unsigned int)((n + 1)/2); i++ )// Выбор номера четного элемента
  14.     {
  15.         for( j = 0; j<i; j++ )
  16.         {
  17.             buffer = array[2*i - j];
  18.             array[2*i - j] = array[2*i - 1 - j];
  19.             array[2*i - 1 - j] = buffer;
  20.         }
  21.     }
  22. }
  23.  
  24. int main(int argc, const char *argv[])
  25. {
  26.     FILE *input_file, *output_file;
  27.     unsigned int n, i;
  28.     double *array;
  29.  
  30.     if( argc!=3 )
  31.     {
  32.         fprintf(stderr, "Usage: %s file_with_array file_for_result\n", argv[0]);
  33.         return -1;
  34.     }
  35.  
  36.     if( !(input_file = fopen(argv[1], "r")) )
  37.     {
  38.         fprintf(stderr, "Can not open file %s\n", argv[1]);
  39.         return -1;
  40.     }
  41.  
  42.     if( fscanf(input_file, "%u", &n)!=1 )
  43.     {
  44.         fprintf(stderr, "Can not read size of array from %s\n", argv[1]);
  45.         fclose(input_file);
  46.         return -1;
  47.     }
  48.  
  49.     if( !(array = (double *)malloc(n*sizeof(double))) )
  50.     {
  51.         fprintf(stderr, "Can not allocate memory!\n");
  52.         fclose(input_file);
  53.         return -1;
  54.     }
  55.  
  56.     for( i = 0; i<n; i++ )
  57.     {
  58.         if( fscanf(input_file, "%lf", array + i)!=1 )
  59.         {
  60.             fprintf(stderr, "Can not read element from %s\n", argv[1]);
  61.             fclose(input_file);
  62.             return -1;
  63.         }
  64.     }
  65.     // Массив считан
  66.  
  67.     fclose(input_file);
  68.  
  69.     f(n, array);
  70.  
  71.     if( !(output_file = fopen(argv[2], "w")) )
  72.     {
  73.         fprintf(stderr, "Can not open/create file %s\n", argv[2]);
  74.         return -1;
  75.     }
  76.  
  77.     fprintf(output_file, "%d\t", n);
  78.     for( i = 0; i<n; i++ )
  79.     {
  80.         fprintf(output_file, "%lf\t", array[i]);
  81.     }
  82.  
  83.     fclose(output_file);
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement