2012-12-04 31 views
0

我正試圖編寫一個程序,它可以計算任何NxN矩陣的行列式,而不管大小如何,但程序有問題崩潰的任何矩陣大小大於1.使用多維數組的遞歸和動態內存分配來查找NxN矩陣的行列式

我會非常感謝任何能告訴我我做錯了什麼的人。我是新來的C++和動態內存的話,把它在我身上容易請(:

這是我的計劃:

#include <iostream> 

using namespace std; 

int determinant(int *matrix[], int size); 
void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column); 

int main() 
{ 
    int size; 
    cout << "What is the size of the matrix for which you want to find the determinant?:\t"; 
    cin >> size; 

    int **matrix; 
    matrix = new int*[size]; 
    for (int i = 0 ; i < size ; i++) 
     matrix[i] = new int[size]; 

    cout << "\nEnter the values of the matrix seperated by spaces:\n\n"; 
    for(int i = 0; i < size; i++) 
     for(int j = 0; j < size; j++) 
      cin >> matrix[i][j]; 

    cout << "\nThe determinant of the matrix is:\t" << determinant(matrix, size) << endl; 

    return 0; 
} 

int determinant(int *matrix[], int size){ 
    if(size==1)return matrix[0][0]; 
    else{ 
     int result=0, sign=-1; 
     for(int j = 0; j < size; j++){ 

      int **minorMatrix; 
      minorMatrix = new int*[size-1]; 
      for (int k = 0 ; k < size-1 ; k++) 
       matrix[k] = new int[size-1]; 

      ijMinor(matrix, minorMatrix, size, 0, j); 

      sign*=-1; 
      result+=sign*matrix[0][j]*determinant(minorMatrix, size-1); 
      for(int i = 0; i < size-1; i++){ 
       delete minorMatrix[i]; 
      } 
     } 

     return result; 
    } 
} 

void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column){ 
    for(int i = 0; i < size; i++){ 
     for(int j = 0; j < size; j++){ 
      if(i < row){ 
       if(j < column)minorMatrix[i][j] = matrix[i][j]; 
       else if(j == column)continue; 
       else minorMatrix[i][j-1] = matrix[i][j]; 
      } 
      else if(i == row)continue; 
      else{ 
       if(j < column)minorMatrix[i-1][j] = matrix[i][j]; 
       else if(j == column)continue; 
       else minorMatrix[i-1][j-1] = matrix[i][j]; 
      } 
     } 
    } 
} 
+1

我會首先建議重構使用[std :: vector](http://www.cplusplus.com/reference/vector/vector/),而不是基於動態內存的數組,以消除「new」和「刪除」。 –

+0

當你執行'new []'時,總是使用'delete []'。 – molbdnilo

+0

感謝您的幫助..該程序正在工作 – theintegral

回答

0

你最好使用C/C++接口BLAS/LAPACK的Fortran在這個任務中做最好的工作的圖書館

首先,你已經在O(N!)中實現了複雜性的數值方法,更不用說你將要介紹的數值不穩定性了;現實世界的系統(它總是使用BLAS軟件包通過首先將N×N矩陣轉換成上/下三角形式,然後找到p主要對角元素的結構。

在經典書籍'Numerical Recipes'或'Matrix Computations'中查找參考資料。

+0

感謝您的幫助和參考。我只是編程的初學者,所以我只是試圖用這個任務來測試我的理解。我並沒有試圖寫出找到行列式的最佳或最有效的程序。儘管如此,非常感謝你,我相信我會發現你給我的參考資料非常有幫助。 – theintegral

1

minorMatrix包括因爲這個未初始化的指針:

minorMatrix = new int*[size-1]; 
for (int k = 0 ; k < size-1 ; k++) 
    matrix[k] = new int[size-1]; 

matrix[k]應該是minorMatrix[k]

+0

非常感謝你的男人。那就是訣竅。當你複製並粘貼而不確定你改變了每個變量時,會發生這種情況。 – theintegral