gpt4 book ai didi

c - 计算矩阵行列式的代码的奇怪输出

转载 作者:行者123 更新时间:2023-11-30 15:43:38 27 4
gpt4 key购买 nike

这是我的代码,它使用拉普拉斯展开式递归地计算矩阵的行列式。当我打印答案时,它以正确的格式打印,但数字不正确。我不知道为什么,希望你们比我了解更多。

#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);
}
}

最佳答案

return(dettemp)det()放错地方了。

函数需要结束

  }
return (dettemp);
}

关于c - 计算矩阵行列式的代码的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com