2017-10-03 7 views
-1

以下のコードは、順序qの行列の行列式を再帰的に計算します。これはq = 3とq = 2で動作しますが、q = 4の場合、プログラムを実行するたびに変化するガベージ値が出力されます: ここで何が問題になりますか?あなたのコードで再帰を伴う行列の決定子

#include <stdio.h> 
#include <math.h> 

int det(int q, int arr[q][q]); 
int main(void) 
{ 
    int arr[4][4] = { 
      {2,4,9,8}, 
      {6,3,4,5}, 
      {5,7,8,6}, 
      {3,2,5,7} 
      }; 
    printf("value of determinant is %d\n", det(4, arr)); 
} 

int det(int q, int arr[q][q]) 
{ 
    if(q>2) 
    { 
    int i, j, k, m, n, s[q-1][q-1], d=0, cof; 
    for(k=-1,i=0,j=0;k<q-1;k++) 
    { 
     i=0;j=0; 
     for(m=1;m<q;m++,i++) 
     { 
      n=0;j=0; 
      for(n,j;n<k+1;n++,j++) 
      { 
       s[i][j] = arr[m][n]; 
      } 
      n=q-1+k; 
      for(n;n<q;n++,j++) 
      { 
       s[i][j] = (arr[m][n]); 
      } 
     } 
     cof = (arr[0][k+1])*(pow(-1,k+1)); 
     d += cof*det(q-1, s); 
    } 
    return d; 
    } 
    else if(q==2) 
    { 
     int d = ((arr[0][0])*(arr[1][1])-(arr[0][1])*(arr[1][0]));  
     return d; 
    } 
} 
+1

デバッガを使用していますか?あなたはブレークポイントでステップアップを試みましたか?どこに問題がありますか? – ryyker

+0

_basic_デバッグを試しましたか? –

+1

これはなぜ再帰を使用していますか?コードが効率的であまりにも読みやすいですか?そして、あなたはなぜあなたのすべての変数にナンセンス名を1つの文字で与えるのですか? – Lundin

答えて

1

、問題の主なルートは、あなたがconcepts.Youは、あなたが使用するアルゴリズムでミスをチェックするために以下のコードを確認することができます決定をリフレッシュ示唆algorithm.Iです。

#include <stdio.h> 
#include <math.h> 

int det(int q, int arr[q][q]); 
int main(void) 
{ 
    int arr[5][5] = { 
      {2,4,9,1,2}, 
      {6,3,4,2,6}, 
      {5,7,8,6,9}, 
      {9,1,5,3,3}, 
      {3,2,5,3,9} 
      }; 
    printf("value of determinant is %d\n", det(5, arr)); 
    return 0; 
} 

int det(int q, int arr[q][q]) 
{ 
    if(q>2) 
    { 
     int resultOfSubStep = 0 ; //Final result that will be returned 
     int smallerMatrix[q-1][q-1] ; //Matrix in which smaller matrix are to be stored which will be given as arguments to det function in current recursion 
     int i = 0 ; 
     for(;i<q;i++){ 
      int j = 0 ; 

      for (;j<q-1;j++) { //This for loop copies the element required from arr into smallerMatrix 
       int counter = 0 ; 
       int k = 0 ; 
       for (;k<q;k++){ 
        if(k == i)continue; 
        smallerMatrix[j][counter] = arr[j+1][k]; 
        counter++; 
       } 
      } 
      int k1 = arr[0][i]*det(q-1, smallerMatrix); //This is the result of determinant of q-1*q-1 matrix 
      resultOfSubStep += pow(-1,i)*k1; //multiplied by -1 or +1 according to the position of root element 
     } 
     return resultOfSubStep; 
    } 
    else if(q==2) 
    { 
     int d = ((arr[0][0])*(arr[1][1])-(arr[0][1])*(arr[1][0])); 
     return d; 
    } 
    else return arr[0][0]; 
} 

コメント欄に、他の方法を求めました。私の意見では、LU分解が最も簡単です。 LU Decompositionにその詳細をチェックすることができます。この方法では、与えられた行列を上三角行列または下三角行列に縮小し、対角要素の積を取る必要があります。再帰の必要はありません。 これが役立つことを願っています。

+0

マイナー: 'else return -1;' - > 'return -1;' 'q <0'を含むすべての病理学的事例をキャッチします。以前の 'q'テストでも' else'の必要はありません。 – chux

+1

@chux私はあなたの提案に応じて答えを修正しました。それは大丈夫ですか?さらなる修正が必要かどうかは教えてください。ありがとうございます。 –

関連する問題