方阵的逆矩阵的求法

用高斯消元法求方阵逆矩阵

#include
#include
using namespace std;

int main()
{
    cout << "输入方阵的行与列:";
    int row, col;
    cin >> row >> col;

    double **matrix = new double*[row];
    double **inverseMatrix = new double*[row];
    for (int i = 0; i < col; ++i)
    {
        matrix[i] = new double[col];
        inverseMatrix[i] = new double[col];
    }

    cout << "输入矩阵:" << endl;
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
            cin >> matrix[i][j];

    cout << "\n原矩阵为:" << endl;
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            cout << setw(4) << matrix[i][j];
        }
        cout << endl;
    }


    //初始化为逆矩阵为单位矩阵
    for (int i = 0;i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
            inverseMatrix[i][j] = 0;
        inverseMatrix[i][i] = 1;
    }

    //矩阵行变换,把原矩阵变换为单位矩阵,单位矩阵采取相同变换后为逆矩阵

    for (int k = 0; k < row; ++k)
    {
        for (int i = 0; i < col; ++i)
        {
            //对角线元素不处理
            if (i == k)
                continue;
            else
            {
                //算出比例
                double ratio = matrix[i][k] / matrix[k][k];

                //Ri = Ri - kRj
                for (int j = 0; j < col; j++)
                {
                    matrix[i][j] -= ratio * matrix[k][j];
                    inverseMatrix[i][j] -= ratio * inverseMatrix[k][j];
                }
            }
        }
    }

    //输出逆矩阵

    cout << "\n逆矩阵为:" << endl;
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            cout << setw(4) << inverseMatrix[i][j];
        }
        cout << endl;
    }

    for (int i = 0; i < col; ++i)
    {
        delete[] matrix[i];
        delete[] inverseMatrix[i];
    }
    delete[]matrix;
    delete[]inverseMatrix;

    system("pause");
    return 0;
}

你可能感兴趣的:(矩阵,算法,数学,矩阵)