好吧,我的任务是创建一个程序,从文件中读取未知矩阵,然后以某种方式计算它的行列式。我几乎完成了所有工作,只是从文件中获取数字后数字似乎乱七八糟。
如果你只看我的代码可能会更容易,这是直到刚读完矩阵的部分,我说的值都是乱七八糟的
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
FILE *input;
int i, j, temp;
int dim=0;
double det;
const char inp_fn[]="matrix.dat";
/*Open File*/
input = fopen(inp_fn, "r");
/*Find the number of lines and hence dimensions*/
while (EOF != (temp = fgetc(input)))
{
if (temp=='\n')
{
++dim;
}
}
/*Reset pointer to beginning of file and float the matrix*/
fseek(input, 0, SEEK_SET);
float matrix[dim][dim];
/*Check file isn't NULL, if good fill the matrix with the values from the file*/
if( (input != (FILE*) NULL) )
{
for(i=0; i<=dim; i++)
{
for(j=0; j<=dim; j++)
{
fscanf(input, "%f", &matrix[i][j]);
}
}
fclose(input);
}
else
{
printf("Could not open file!\n");
}
如果你们能看到任何东西,请告诉我,我对此很陌生,所以我可能遗漏了一些明显的东西,谢谢。
最佳答案
for(i=0; i<=dim; i++)
{
for(j=0; j<=dim; j++)
{
fscanf(input, "%f", &matrix[i][j]);
}
}
必须是i < dim
和 j < dim
.
数组的索引以 0 开头,而不是 1。
关于c - 未正确读取矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749790/