所以这是我的代码,它使用拉普拉斯的扩展递归计算矩阵的行列式。当我打印答案时,它以正确的格式打印,但数字不正确。我不知道为什么,希望你们比我更了解。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Define a determinant for a certain matrix and dimension size*/
double det(double **mattemp, int size);
/*Find the values for our matrix and it's dimension*/
int main(int argc, char* argv[])
{
FILE *input;
int i, j, pos;
int dim=1;
double **matrix;
/*Open File*/
input = fopen("matrix.dat", "r");
/*Check file isn't NULL, if good find the no of lines and hence dimensions*/
if( (input != (FILE*) NULL) )
{
while (EOF != (pos = fgetc(input)))
{
if (pos == '\n')
{
++dim;
}
}
}
else
{
printf("********************\n");
printf("Could not open file!\n");
printf("********************\n");
return(EXIT_FAILURE);
}
/*Close and reopen file and set the matrix*/
fclose(input);
input = fopen("matrix.dat", "r");
matrix=(double**)malloc(dim*sizeof(double));
/*Fill the matrix with values from the file*/
for(i=0; i<dim; i++)
{
matrix[i]=(double*)malloc(dim*sizeof(double));
}
for(i=0; i<dim; i++)
{
for(j=0; j<dim; j++)
{
fscanf(input, "%lf", &matrix[i][j]);
}
}
/*Close the file*/
fclose(input);
/*Print the matrix*/
for(i=0; i<dim; i++)
{
printf("| ");
for(j=0; j<dim; j++)
{
printf("%lf ", matrix[i][j]);
}
if(i != dim/2)
{
printf("|\n");
}
else
{
printf("| = %lf \n", det(matrix, dim) );
}
}
return(EXIT_SUCCESS);
}
double det(double **mattemp, int size)
{
double dettemp, **temp;
int j, itemp, jtemp, jcurr;
double column[size];
dettemp = 0;
if(size==1)
{
dettemp = mattemp[0][0];
}
else if(size==2)
{
dettemp = ((mattemp[0][0]*mattemp[1][1])-(mattemp[0][1]*mattemp[1][0]));
}
else
{
for (j=0; j<size; j++)
{
temp = malloc((size-1)*sizeof(*temp));
for(itemp=0; itemp<(size-1); itemp++)
{
temp[itemp]=malloc((size-1)*sizeof(double*));
}
for(itemp=1; itemp<size; itemp++)
{
jtemp=0;
for(jcurr=0; jcurr<size; jcurr++)
{
if(jcurr==j)
{
continue;
}
temp[itemp-1][jtemp] = mattemp[itemp][jcurr];
jtemp++;
}
}
dettemp += (mattemp[0][j]*pow(-1,j)*det(temp, size-1));
}
return(dettemp);
}
}
答案 0 :(得分:1)
return(dettemp)
中的det()
放错地方了。
功能需要结束
}
return (dettemp);
}