【发布时间】:2015-12-30 17:29:22
【问题描述】:
我正在尝试编写一个代码来计算 nXn 矩阵的行列式。 对于 3x3 矩阵,代码运行良好,但在 4X4 或更大的矩阵上,程序会崩溃。 你能告诉我我做错了什么吗?
#include<stdio.h>
#include<stdlib.h>
double sum(int n, double **matrix);
int main(){
double row, col, size;
int i,j,k;
FILE *fd=fopen("input10.txt","r");
fscanf(fd,"%lf", &size);
row = size;
col = size;
double ** matrix=(double **) malloc (row*sizeof (double*));
if(matrix != NULL){
for(k=0; k<row ;k++){
matrix[k]=(double*) calloc (col,sizeof (double));
}
}
for(i=0; i<row; i++){
for(j=0; j<col; j++){
fscanf(fd,"%lf",&matrix[i][j]);
}
}
printf("%.2le",sum(size,matrix));
return 0;
}
double computeDeterminant(unsigned char end, unsigned char start, double **matrix)
{
int i,j,k;
double s=0;
double row, col;
row = end;
col = end;
double ** b=(double **) malloc (row*sizeof (double*));
if(matrix != NULL){
for(k=0; k<row ;k++){
b[k]=(double*) calloc (col,sizeof (double));
}
}
for(i=0;i<end;i++){
for(j=0;j<end;j++){
b[i][j]=matrix[i][j];
}
}
for(i=0;i<end-1;i++){
for(j=1;j<=end;j++){
b[i][j]=b[i+1][j];
}
}
for(i=0;i<end-1;i++){
for(j=start;j<=end-1;j++){
b[i][j]=b[i][j+1];
}
}
if (end-1==2){
return b[1][1]*b[2][2]-b[1][2]*b[2][1];
}
else{
for (j=0;j<end-1;j++){
s=s+pw(1+j)*b[1][j]*computeDeterminant(end-1,j,b);
}return s;
}
}
double sum(int n,double **matrix)
{
int j;
double s=0;
if(n>2)
{
for(j=1;j<=n;j++)
s=s+pw(1+j)*matrix[1][j]*computeDeterminant(n, j, matrix);
return s;
}
else
return matrix[1][1]*matrix[2][2]-matrix[1][2]*matrix[2][1];
}
int pw(int y)
{
return (y%2)==0?1:-1;
}
【问题讨论】:
-
为什么行和列都是浮点变量!?
-
@cad 以防万一他有一个真的大矩阵。 :)
-
@Barmar 这可能是一个真正参差不齐的矩阵。
-
if(matrix != NULL)需要采取比跳过直接代码块并继续使用NULL值matrix更激烈的行动。