C语言 计算 NxN 矩阵的行列式的 C 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41384020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C program to calculate the determinant of a NxN matrix
提问by Edward
I'm trying to write a program that would calculate the determinant for me, and this is what I've done so far. But it's not working it just prints 6356918 for every matrix I throw at it. I've even compared my code to some other codes on the internet but that didn't work.
我正在尝试编写一个程序来为我计算行列式,这就是我迄今为止所做的。但它不起作用,它只是为我扔给它的每个矩阵打印 6356918。我什至将我的代码与互联网上的其他一些代码进行了比较,但这没有用。
And I don't know anything about pointers so I cannot use them. I tried debugging which I don't know much about it either, but there seems to be something wrong with the first 'if' in the second function and the last part of the code which calculates the determinant. I'm coding in code::blocks.
而且我对指针一无所知,所以我无法使用它们。我尝试了调试,我对它也不太了解,但是第二个函数中的第一个“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;
}
采纳答案by Weather Vane
In function det()you have initialised determinantonly when it was not necessary
在函数中,det()您determinant仅在不需要时才初始化
determinant = 0;
determinant = A[0][0]*A[1][1]-A[0][1]*A[1][0];
but when it was needed
但在需要的时候
determinant = determinant + O*(A[0][i]*det(Minor,n-1));
there was no previous initialisation. So move
之前没有初始化。所以动
determinant = 0;
to above if(n == 2)near the start of the function.
到if(n == 2)函数开始附近的上方。

