用C程序计算NxN矩阵的行列式 [英] C program to calculate the determinant of a NxN matrix

查看:277
本文介绍了用C程序计算NxN矩阵的行列式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来为我计算行列式,这是我到目前为止所做的.但是它不起作用,它只会为我向其抛出的每个矩阵打印6356918.我什至已经将我的代码与互联网上的其他一些代码进行了比较,但这没用.

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.

我对指针一无所知,因此无法使用它们.我尝试了调试,对此我也不是很了解,但是第二个函数中的第一个"if"和计算行列式的代码的最后一部分似乎出了点问题.我正在用代码::: blocks进行编码.

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.

#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

In function det() you have initialised determinant only when it was not necessary

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));

没有先前的初始化.因此,移动

there was no previous initialisation. So move

determinant = 0;

在函数开始附近的if(n == 2)上方.

to above if(n == 2) near the start of the function.

这篇关于用C程序计算NxN矩阵的行列式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆