2017-10-03 6 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

왜이 용도로 재귀를 사용하고 있습니까? 코드가 너무 효율적이고 읽기 어려웠습니다. 그리고 왜 모든 변수에 난센스 이름을 하나의 문자로 제공합니까? – 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 귀하의 제안에 따라 답변을 수정했습니다. 괜찮습니까? 추가 수정이 필요한지 알려주세요. 감사합니다. –