c程序设计中函数递归nxn矩阵的行列式



我想纠正这段代码来计算nxn矩阵的行列式。下面的代码是我迄今为止所做的工作。但它给出了最多3x3个矩阵的正确答案,而比这更大的是它给出了错误的值。我还单独检查了由主矩阵形成次矩阵的部分,它工作得很好。我仍然不知道为什么它会为4x4和更大的矩阵返回错误的值?

#include <stdio.h> 
#include <conio.h>
#include <stdlib.h>
#include <math.h>
int dete(int, int (*)[]);
int main()
{
int a[3][3]=
{
1,4,3,
2,1,5,
3,2,1
};
int b[4][4]=
{
5,3,-2,-6,
1,2,7,4,
-10,3,5,-3,
-4,2,6,1
};
int ans1,ans2;
ans1=dete(3,a);//ans1 = 46 and this is correct
ans2=dete(4,b);//ans2 = 174 but it is giving 5169 which is wrong
printf("%d, %d", ans1, ans2);
getch();
}
int dete(int row, int arr[][row])
{
int col_main_mark,col_main,row_main,col_minor,cof,x,y;
int minor[row-1][row-1];
static int det=0;
if(row==2)//condition to stop recursion
{
det = arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0];
return det;
}
for(col_main_mark=0; col_main_mark<row; col_main_mark++)//for specific col value of main matrix (arr[row][row])
{
cof=arr[0][col_main_mark];
//following two loop will make the minor matrix (minor[row-1][row-1]) from the main marix
for(row_main=0; row_main<row; row_main++)
{
for(col_main=0,col_minor=0; col_main<row; col_main++)
{
if(col_main==col_main_mark)
continue;
minor[row_main][col_minor]=arr[row_main+1][col_main]; col_minor++;
}
}
det = det + cof * pow(-1,col_main_mark) * dete(row-1, minor);  
}
return det;
}

解决方案是删除static。变量det仅在函数第一次运行时为零。下一次它将具有与上次调用结束时相同的值。

您可以尝试在一行中使用两个或多个3x3矩阵。只有对dete的第一次调用才会产生正确的结果。

最新更新