我编写了这个程序,它使用递归来计算矩阵的行列式。我的函数有问题build_new_matrix
(它不是递归的),因为它改变了变量old_mat
,虽然我不明白为什么!
#include <iostream>
#include <cstring>
using namespace std;
int * new_mat = new int[];
int calculate_det_small (int matrix [4]){ //calculate determinant of a 2x2 matrix
int res = ((matrix[0])*(matrix[3]))-((matrix[1])*(matrix[2]));
return res;
};
int * build_new_matrix (int* old_mat, int rows, int minor){ //return the minor of the matrix
int l=0;
for (int i=rows; i<(rows*rows); i++){
cout<<old_mat[i]<<" ";
if ((i-minor) % rows !=0){
new_mat [l] = old_mat[i] ; ///////////////////error!!!!!!!!
l++;
}
};
return new_mat;
};
int calculate_det (int rows, int matrix[]) { //calculate determinant of a bigger matrix
int c,o;
if (rows==2){
return calculate_det_small (matrix);
}
else {
int result=0;
for (int i=0; i<rows;i++){
int* cur_matrix = build_new_matrix(matrix,rows,i);
if (i%2==0){
c = matrix[i];
result+= ((matrix[i])*(calculate_det((rows-1),cur_matrix)));
}
else{
o =matrix[i];
result-= ((matrix[i])*(calculate_det((rows-1),cur_matrix)));
}
};
return result;
}
};
void main(){
int mat[16] = {1,2,3,4,5,6,7,8,9, 10, 11, 12, 10, 14 ,15, 16};
int determinanta = calculate_det(4,mat);
}