【发布时间】:2020-03-11 23:58:04
【问题描述】:
我想更正此代码以计算 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 int det=0;中删除static -
你为什么把
static放在int det=0;之前?你在那里的思考过程是什么?也许你对它的作用有误解。 -
这是minimal reproducible example 的一个很好的例子。干得好。