Advertisement
RobertDeMilo

Основы С++2.4 Алгоритмы sort и reverse / Задача 2 Медиана

Sep 23rd, 2023
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. pair<bool, double> CalcMedian(vector<double> samples) {
  8.     if (samples.empty()) {
  9.         return {false, 0.0};
  10.     }
  11.     sort(samples.begin(), samples.end());
  12.     int index = samples.size() / 2;
  13.     if (samples.size() % 2 == 0) {
  14.         return {true, (samples[index - 1] + samples[index]) / 2};
  15.     }
  16.  
  17.     return {true, samples[index]};
  18. }
  19.  
  20. int main() {
  21.     int size;
  22.     cin >> size;
  23.  
  24.     vector<double> samples;
  25.     for (int i = 0; i < size; ++i) {
  26.         double sample;
  27.         cin >> sample;
  28.         samples.push_back(sample);
  29.     }
  30.  
  31.     const auto [median_exists, median_value] = CalcMedian(samples);
  32.     if (median_exists) {
  33.         cout << median_value << endl;
  34.     } else {
  35.         cout << "Empty vector"s << endl;
  36.     }
  37. }
  38. ******************************************************************************************************
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement