Advertisement
Solingen

z14.1.cpp

Dec 22nd, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     int m, n;
  7.     cout << "Введите размеры матрицы m, n: ";
  8.     cin >> m >> n;
  9.  
  10.     double** A = new double*[m];
  11.     for(int i = 0; i < m; i++)
  12.     {
  13.         A[i] = new double[n];
  14.     }
  15.  
  16.     // Считываем
  17.     for(int i = 0; i < m; i++)
  18.     {
  19.         for(int j = 0; j < n; j++)
  20.         {
  21.             cin >> A[i][j];
  22.         }
  23.     }
  24.  
  25.     // Метод Гаусса, но без вектора правой части (просто матрица)
  26.     int rank = 0;
  27.     int row = 0;
  28.     for(int col = 0; col < n && row < m; col++)
  29.     {
  30.         // Находим непустую строку
  31.         int pivotRow = row;
  32.         while(pivotRow < m && A[pivotRow][col] == 0.0)
  33.         {
  34.             pivotRow++;
  35.         }
  36.         if(pivotRow == m) continue; // нет ведущего элемента в этом столбце
  37.  
  38.         // Меняем строки
  39.         if(pivotRow != row)
  40.         {
  41.             for(int k = 0; k < n; k++)
  42.             {
  43.                 double temp = A[row][k];
  44.                 A[row][k] = A[pivotRow][k];
  45.                 A[pivotRow][k] = temp;
  46.             }
  47.         }
  48.  
  49.         // Нормируем
  50.         double pivot = A[row][col];
  51.         for(int c = col; c < n; c++)
  52.         {
  53.             A[row][c] /= pivot;
  54.         }
  55.  
  56.         // Зануляем
  57.         for(int r = row+1; r < m; r++)
  58.         {
  59.             double factor = A[r][col];
  60.             for(int c = col; c < n; c++)
  61.             {
  62.                 A[r][c] -= factor * A[row][c];
  63.             }
  64.         }
  65.  
  66.         rank++;
  67.         row++;
  68.     }
  69.  
  70.     cout << "Ранг = " << rank << endl;
  71.  
  72.     // Освобождаем
  73.     for(int i = 0; i < m; i++)
  74.     {
  75.         delete[] A[i];
  76.     }
  77.     delete[] A;
  78.  
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement