Advertisement
Lavig

Другий семестр. Лабораторна робота №14-15 (Завдання 2)

Apr 20th, 2025
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <windows.h>
  3. #include <vector>
  4. #include <format>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     SetConsoleOutputCP(1251);
  11.     SetConsoleCP(1251);
  12.     srand(time(0));
  13.     vector<double> numbers{};
  14.     double temp_number{}, S{}, difference{}, max_difference{};
  15.     int N{}, i{}, index{};
  16.     while (true) {
  17.         cout << "Введіть бажану кількість елементів у масиві (від 2 до 10): ";
  18.         cin >> N;
  19.         if (cin.fail() || cin.peek() != '\n' || N < 2 || N > 10) {
  20.             cin.clear();
  21.             cin.ignore(32767, '\n');
  22.             cout << "Число було введено неправильно. Спробуйте ще раз!" << endl;
  23.             continue;
  24.         }
  25.         else {
  26.             break;
  27.         }
  28.     }
  29.     cout << "Згенерований масив: ";
  30.     for (i = 0; i < N; i++) {
  31.         temp_number = (rand() % 199 + 1 - 100) + (rand() % 100 + 1) / 100.0;
  32.         numbers.push_back(temp_number);
  33.         cout << format("{:8.2f}", temp_number) << " ";
  34.     }
  35.     cout << endl;
  36.     while (true) {
  37.         cout << "Введіть число S: ";
  38.         cin >> S;
  39.         if (cin.fail()) {
  40.             cin.clear();
  41.             cin.ignore(32767, '\n');
  42.             cout << "Число було введено неправильно. Спробуйте ще раз!" << endl;
  43.             continue;
  44.         }
  45.         else {
  46.             break;
  47.         }
  48.     }
  49.     max_difference = fabs(numbers[0] - S);
  50.     for (int i = 1; i < numbers.size(); i++) {
  51.         difference = fabs(numbers[i] - S);
  52.         if (difference > max_difference) {
  53.             max_difference = difference;
  54.             index = i;
  55.         }
  56.     }
  57.     cout << "Найбільш віддалений елемент: " << numbers[index] << endl;
  58.     cout << "Його індекс: " << index << endl;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement