Advertisement
SomniP

Замена максимального double элемента на СГ полож. элем.

Dec 2nd, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <windows.h>
  3. #include <ctime>
  4. #include <algorithm>
  5. #include <numeric>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. void set_arr(double *);
  11.  
  12. void f(double *);
  13.  
  14. void show(double *);
  15.  
  16. int main()
  17. {
  18.     SetConsoleCP(1251);
  19.     SetConsoleOutputCP(1251);
  20.     srand(time(NULL));
  21.     system("color 0A");
  22.  
  23.     auto arr = new double[10u + rand() % 11u];
  24.     set_arr(arr);
  25.     cout << "Исходный массив" << endl;
  26.     show(arr);
  27.     f(arr);
  28.     cout << "Обработанный массив" << endl;
  29.     show(arr);
  30.  
  31.     system("pause");
  32.     return 0;
  33. }
  34.  
  35. void set_arr(double *a)
  36. {
  37.     auto len = _msize(a) / (2u * sizeof(a));
  38.     auto filler = []()
  39.     {
  40.         return -10 + 20 * (rand() / static_cast<double>(RAND_MAX));
  41.     };
  42.     generate(a, a + len, filler);
  43.     a[rand() % len] = rand() % 11;
  44. }
  45.  
  46. void f(double *a)
  47. {
  48.     auto len = _msize(a) / (2u * sizeof(a));
  49.     auto count_positive = 0u;
  50.     auto max = a[0u];
  51.     auto collection = [&count_positive, &max](double p, double t) -> double
  52.     {
  53.         if (t > 0)
  54.         {
  55.             if (t > max)
  56.                 max = t;
  57.             ++count_positive;
  58.             return p *= t;
  59.         }
  60.         else
  61.         {
  62.             return p;
  63.         }
  64.     };
  65.     auto p = accumulate(a, a + len, 1., collection);
  66.     auto avg_geom = pow(p, 1. / count_positive);
  67.     auto swp = [max, avg_geom](double &t)
  68.     {
  69.         if (t == max)
  70.         {
  71.             t = avg_geom;
  72.         }
  73.     };
  74.     for_each(a, a + len, swp);
  75. }
  76.  
  77. void show(double *a)
  78. {
  79.     auto len = _msize(a) / (2u * sizeof(a));
  80.     for (auto it = a; it != a + len; ++it)
  81.     {
  82.         cout << *it << endl;
  83.     }
  84.     cout << endl;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement