Advertisement
Solingen

z13.3.cpp

Dec 22nd, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | None | 0 0
  1. #include <iostream>
  2. #include "string.h"
  3. #include "array.h"
  4. using namespace std;
  5.  
  6. // Функция для решения методом Гаусса
  7. Array<double> gaussSolve(Array<Array<double>>& A, Array<double>& b)
  8. {
  9.     int n = A.size();
  10.     // Расширенная матрица
  11.     // (Но давайте для удобства будем хранить всё в A, а b — в последнем столбце)
  12.     // Перенесём b[i] в A[i][n]
  13.     for(int i = 0; i < n; i++)
  14.     {
  15.         A[i].append(b[i]);
  16.     }
  17.  
  18.     // Прямой ход
  19.     for(int i = 0; i < n; i++)
  20.     {
  21.         double pivot = A[i][i];
  22.         // нормируем
  23.         for(int col = i; col <= n; col++)
  24.         {
  25.             A[i][col] /= pivot;
  26.         }
  27.         // зануляем остальные
  28.         for(int r = i+1; r < n; r++)
  29.         {
  30.             double factor = A[r][i];
  31.             for(int c = i; c <= n; c++)
  32.             {
  33.                 A[r][c] -= factor * A[i][c];
  34.             }
  35.         }
  36.     }
  37.  
  38.     // Обратный ход
  39.     Array<double> x;
  40.     for(int i = 0; i < n; i++)
  41.     {
  42.         x.append(0.0);
  43.     }
  44.     for(int i = n-1; i >= 0; i--)
  45.     {
  46.         double val = A[i][n];
  47.         for(int c = i+1; c < n; c++)
  48.         {
  49.             val -= A[i][c] * x[c];
  50.         }
  51.         x[i] = val;
  52.     }
  53.  
  54.     return x;
  55. }
  56.  
  57. int main()
  58. {
  59.     cout << "Введите n: ";
  60.     int n;
  61.     cin >> n;
  62.  
  63.     Array<Array<double>> mat;
  64.     mat.append(Array<double>()); // чтобы избежать проблем, но лучше сразу resize
  65.     mat = Array<Array<double>>(); // заново инициализируем
  66.  
  67.     // Инициализируем матрицу A
  68.     for(int i = 0; i < n; i++)
  69.     {
  70.         Array<double> row;
  71.         for(int j = 0; j < n; j++)
  72.         {
  73.             double tmp;
  74.             cin >> tmp;
  75.             row.append(tmp);
  76.         }
  77.         mat.append(row);
  78.     }
  79.  
  80.     // Считываем b
  81.     Array<double> b;
  82.     for(int i = 0; i < n; i++)
  83.     {
  84.         double tmp;
  85.         cin >> tmp;
  86.         b.append(tmp);
  87.     }
  88.  
  89.     // Решаем
  90.     Array<double> solution = gaussSolve(mat, b);
  91.  
  92.     // Вывод
  93.     for(int i = 0; i < n; i++)
  94.     {
  95.         cout << "x[" << i << "] = " << solution[i] << endl;
  96.     }
  97.  
  98.     return 0;
  99. }
  100.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement