【问题标题】:Determinant of a nxn matrix with function recursion in c programmingc编程中具有函数递归的nxn矩阵的行列式
【发布时间】: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 的一个很好的例子。干得好。

标签: c recursion matrix


【解决方案1】:

解决方法是删除static。变量det 只会在函数第一次运行时为零。下一次它将具有与上次调用结束时相同的值。

您可以尝试连续使用两个或多个 3x3 矩阵。只有第一次调用 dete 才会产生正确的结果。

【讨论】:

  • 我试过删除 static 关键字,也试过连续使用 2 个或更多 3x3 矩阵,效果很好。我还使 det 全局化,它也仅适用于 3x3 矩阵。但这些都不适用于 4x4 或更大尺寸的矩阵。现在该怎么办?
  • @AbhirupBakshi 但是为什么你不能让它成为一个局部变量呢?将其设置为静态或全局毫无意义。
  • 是的,我把它变成了一个自动变量,它工作了。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
相关资源
最近更新 更多