C程序计算NxN矩阵的行列式

标签 c arrays

我正在尝试编写一个程序来为我计算行列式,这就是我到目前为止所做的。但它不起作用它只是为我扔给它的每个矩阵打印 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/

相关文章:

c - 为什么在c中的结构中使用两个指针

c - 为什么编译器不优化掉这些无法访问的指令呢?

arrays - 如何检查我的字典数组是否有某个字典?

c++ - 关于C/C++中函数指针的问题

c - Atom.io 缺少 sys/wait.h 或允许 fork()

c - 尝试列出数组内容时出现无法解释的格式

php - sql、返回和格式化所有数组数据的正确方法是什么?

php通过 session 数组检查元素是否存在

c++ - 无法让数组正确更新

javascript - JS中用数组元素替换var字符串中的单词