//********************************
//*** 求任何一个实矩阵的逆***
//********************************
#include <math.h>
#include <malloc.h>
#include <iostream>
#include <iomanip>
using namespace std;
#define N 10 //定义方阵的最大阶数为10
//函数的声明部分
float MatDet(float *p, int n); //求矩阵的行列式
float Creat_M(float *p, int m, int n, int k); //求矩阵元素A(m, n)的代数余之式
void print(float *p, int n); //输出矩阵n*n
bool Gauss(float A[][N], float B[][N], int n); //采用部分主元的高斯消去法求方阵A的逆矩阵B
int main()
{
float *buffer, *p; //定义数组首地址指针变量
int row, num; //定义矩阵的行数和矩阵元素个数
int i, j;
float determ; //定义矩阵的行列式
float a[N][N], b[N][N];
int n;
cout << "采用逆矩阵的定义法求矩阵的逆矩阵!\n";
cout << "请输入矩阵的行数: ";
cin >> row;
num = 2 * row * row; //row*row再乘以2的原因可能是为了下一条语句中申请更多的内存单元
buffer = (float *)calloc(num, sizeof(float)); //分配内存单元
p = buffer;
if (NULL != p)
{
for (i = 0; i < row; i++)
{
cout << "Please input the number of " << i+1 << " row: ";
for (j = 0; j < row; j++)
{
cin >> *p++;
}
}
}
else
{
cout << "Can't distribute memory\n";
}
cout << "The original matrix : \n";
print(buffer, row); //打印该矩阵
determ = MatDet(buffer, row); //求整个矩阵的行列式
p = buffer + row * row;
if (determ != 0)
{
cout << "The determinant of the matrix is " << determ << endl;
for (i = 0; i < row; i++) //求逆矩阵
{
for (j = 0; j < row; j++)
{
*(p+j*row+i) = Creat_M(buffer, i, j, row)/determ;
}
}
cout << "The inverse matrix is: " << endl;
print(p, row); //打印该矩阵