我正在尝试编写一个程序来为我计算行列式,这就是我到目前为止所做的。但它不起作用它只是为我扔给它的每个矩阵打印 6356918。我什至将我的代码与互联网上的其他一些代码进行了比较,但没有用。
而且我对指针一无所知,所以我不能使用它们。我尝试调试,对此我也不太了解,但第二个函数中的第一个“if”和计算行列式的代码的最后部分似乎有问题。我在 code::blocks 中编码。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
main()
{
int A[100][100];
int i,j,k,n,res;
printf("Enter the order of the matrix: \n");
scanf("%d",&n);
printf("\nEnter the elements of the matrix one by one: \n");
for(i = 0 ; i < n ; i++)
{
for(j = 0 ; j < n ; j++)
{
scanf("%d",&A[i][j]);
}
}
for(i = 0 ; i < n ; i++)
{
for(j = 0 ; j < n ; j++)
{
printf("%5d",A[i][j]);
}
printf("\n");
}
res = det(A,n);
printf("%d",res);
}
int det(int A[100][100], int n)
{
int Minor[100][100];
int i,j,k,c1,c2;
int determinant;
int c[100];
int O=1;
if(n == 2)
{
determinant = 0;
determinant = A[0][0]*A[1][1]-A[0][1]*A[1][0];
return determinant;
}
else
{
for(i = 0 ; i < n ; i++)
{
c1 = 0, c2 = 0;
for(j = 0 ; j < n ; j++)
{
for(k = 0 ; k < n ; k++)
{
if(j != 0 && k != i)
{
Minor[c1][c2] = A[j][k];
c2++;
if(c2>n-2)
{
c1++;
c2=0;
}
}
}
}
determinant = determinant + O*(A[0][i]*det(Minor,n-1));
O=-1*O;
}
}
return determinant;
}
最佳答案
在函数 det()
中,您仅在不需要时才初始化了行列式
determinant = 0;
determinant = A[0][0]*A[1][1]-A[0][1]*A[1][0];
但在需要的时候
determinant = determinant + O*(A[0][i]*det(Minor,n-1));
之前没有初始化。所以动起来
determinant = 0;
在函数开始附近的 if(n == 2)
之上。
关于C程序计算NxN矩阵的行列式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384020/