#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
double a[10][10];//保存所要求的矩阵
double b[10][10];//保存某项除去改行该列所得的矩阵
double c[10][10];//保存伴随矩阵
int caculate(double a[10][10], int n)
{
int m, j, k;
int sum = 0, count1 = 0, count2 = 0;
if (n == 1) return a[0][0];
for (j = 0; j < n; j++)
{
double b[10][10] = { 0 };//循环清零数组,二维数组不用memset函数清零,易错
count1 = 0, count2 = 0;
for (m = 1; m < n; m++)//即要除去的行,因为其不随着a数组行变化,故无需再加第四层外循环
{
for (k = 0; k < n; k++)
{
if (k == j)//跳过所要除去的列
continue;
else
b[count1][count2++] = a[m][k];
}
count1++;
count2 = 0;
}
sum += a[0][j] * (int)pow(-1, j) * caculate(b, n - 1);
}
return sum;
}
//计算矩阵的行列式的值
int main()
{
int i, j, n, m, k, count1, count2;
int sum;
while (cin >> n)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cin >> a[i][j];
}
sum = caculate(a, n);//计算所求矩阵的行列式
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
double b[10][10] = { 0 };//清零数组
count1 = 0, count2 = 0;
for (m = 0; m < n; m++)
{
if (m == i) continue;//跳过所要除去的行
for (k = 0; k < n; k++)
{
if (k == j) continue;//跳过所要除去的列
b[count1][count2++] = a[m][k];//保存某项除去改行该列所得的矩阵
}
count1++;
count2 = 0;
}
c[j][i] = pow(-1, i + j) * caculate(b, n - 1);//计算代数余子式并保存
if (c[j][i] == 0) c[j][i] = 0;
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cout << c[i][j] << " ";
cout << endl;
}
cout << endl;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
cout << c[i][j] / sum << " ";//求逆矩阵
cout << endl;
}
cout << endl;
}
}
改编于博主"不想WA"