abubaca

Untitled

Apr 25th, 2020
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <utility>
  5.  
  6. using namespace std;
  7.  
  8. vector<double> gauss(vector<vector<double>>& a, vector<double>& y, int n)
  9. {
  10.     const double eps = 0.00001;
  11.     double max;
  12.     int k, index;
  13.     k = 0;
  14.     while (k < n)
  15.     {
  16.         max = abs(a[k][k]);
  17.         index = k;
  18.         for (int i = k + 1; i < n; i++)
  19.             if (abs(a[i][k]) > max)
  20.             {
  21.                 max = abs(a[i][k]);
  22.                 index = i;
  23.             }
  24.         if (max < eps)
  25.         {
  26.             cout << "Решение получить невозможно из-за нулевого столбца ";
  27.             cout << index << " матрицы A" << endl;
  28.             return vector<double>();
  29.         }
  30.         for (int j = 0; j < n; j++)
  31.             swap(a[k][j], a[index][j]);
  32.         swap(y[k], y[index]);
  33.         for (int i = k; i < n; i++)
  34.         {
  35.             double temp = a[i][k];
  36.             if (abs(temp) < eps) continue;
  37.             for (int j = 0; j < n; j++)
  38.                 a[i][j] /= temp;
  39.             y[i] /= temp;
  40.             if (i == k) continue;
  41.             for (int j = 0; j < n; j++)
  42.                 a[i][j] -= a[k][j];
  43.             y[i] -= y[k];
  44.         }
  45.         k++;
  46.     }
  47.     vector<double> x(n);
  48.     for (k = n - 1; k >= 0; k--)
  49.     {
  50.         x[k] = y[k];
  51.         for (int i = 0; i < k; i++)
  52.             y[i] -= a[i][k] * x[k];
  53.     }
  54.     return x;
  55. }
  56.  
  57.  
  58. int main()
  59. {
  60.     setlocale(LC_ALL, "Russian");
  61.     int n;
  62.     cout << "Введите порядок системы\n";
  63.     cin >> n;
  64.     vector<vector<double>> mat(n, vector<double>(n));
  65.     cout << "Введите коэфиценты системы\n";
  66.     for (int i = 0; i < n; i++)
  67.         for (int j = 0; j < n; j++)
  68.             cin >> mat[i][j];
  69.     cout << "Введите свободные члены\n";
  70.     vector<double> free(n);
  71.     for (int i = 0; i < n; i++)
  72.         cin >> free[i];
  73.  
  74.     vector<double> result = gauss(mat, free, n);
  75.  
  76.     if (result.size() == 0)
  77.         return 0;
  78.  
  79.     cout << endl;
  80.  
  81.     for (int i = 0; i < n; i++)
  82.     {
  83.         cout << endl;
  84.         for (int j = 0; j < n; j++)
  85.             cout << mat[i][j] << " ";
  86.         cout << free[i];
  87.     }
  88.     cout << endl;
  89.     cout << "Корни\n";
  90.     for (int i = 0; i < n; i++)
  91.         cout << result[i] << " ";
  92. }
Advertisement
Add Comment
Please, Sign In to add comment