好吧,我的任务是创建一个程序,它从文件中读取未知的nxn矩阵,然后以某种方式计算它的行列式。我已经完成了大部分工作,除了从文件中获取数字之后,这些数字似乎已经变得越来越混乱了。从C中的文件获取矩阵C
如果你只是看我的代码,这可能会更容易,这是直到阅读矩阵之后的部分,我说的值都混乱了。这不是我< =昏暗,因为昏暗从0计数,所以它应该运行正确的次数。
#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");
}
所以揭掉,如果你们能看到什么,请告诉我,我真的很新的这所以我可能失去了一些东西很明显,谢谢。
你的文件在最后一行之后是否有'\ n'? – Inspired
此外,最有可能不会导致你的错误,但检查'输入!=(FILE *)NULL'应执行之前的第一个循环计数行数。 – Inspired
用完循环中的界限,请使用'<'而不是'<='。 – dnk