kxcoze

lab22_10_2

Sep 7th, 2020 (edited)
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3.  
  4. using namespace std;
  5.  
  6. void print(double *x, int n);
  7. double negativeIndex(double *x, int n);
  8. double sumNegative(double *x, int n, int ind);
  9. void sort(double *x, int n);
  10.  
  11. int main() {
  12.     setlocale(LC_ALL, "rus");
  13.     srand(time(NULL));
  14.     int n, nInd;
  15.     cout << "Введите кол-во элементов массива: ";
  16.     cin >> n;
  17.  
  18.     double *arr = new double[n];
  19.     for (int i = 0; i < n; i++)
  20.         arr[i] = (((double)rand() / RAND_MAX) * 4) - 2;
  21.  
  22.     cout << "Вывод массива: " << endl;
  23.     print(arr, n);
  24.  
  25.     nInd = negativeIndex(arr, n);
  26.     if (nInd != -1)
  27.         cout << "Сумма элементов после отр. эл. до другого отр. эл. или до конца: " << sumNegative(arr, n, nInd) << endl << endl;
  28.     else
  29.         cout << "Отрицательных чисел нету!" << endl << endl;
  30.    
  31.     sort(arr, n);
  32.     cout << "Отсортированный массив: " << endl;
  33.     print(arr, n);
  34.  
  35.     delete[] arr;
  36.     return 0;
  37. }
  38.  
  39. void print(double *x, int n) {
  40.     for (int i = 0; i < n; i++)
  41.         cout << x[i] << ' ';
  42.     cout << endl;
  43. }
  44.  
  45. double negativeIndex(double *x, int n) {
  46.     int ind = -1;
  47.     for (int i = 0; i < n; i++) {
  48.         if (x[i] < 0) {
  49.             ind = i;
  50.             break;
  51.         }
  52.     }
  53.     return ind;
  54. }
  55.  
  56. double sumNegative(double *x, int n, int ind) {
  57.     double s = 0;
  58.     for (int i = ind + 1; i < n; i++) {
  59.         if (!(x[i] < 0))
  60.             s += x[i];
  61.         else break;
  62.     }
  63.     return s;
  64. }
  65.  
  66. void sort(double *x, int n) {
  67.     for (int i = 1; i < n; i++) {
  68.         int cur = i;
  69.         while (!(abs(x[cur - 1]) < 1) && abs(x[cur]) < 1 && cur > 0) {
  70.             swap(x[cur - 1], x[cur]);
  71.             cur--;
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment