从文件中读取矩阵并计算行列式(C)
所以我写了一些代码,从一个文件中提取一个矩阵,把它放到一个数组中,然后计算它的行列式。但是,在运行时,数组似乎尚未填充,程序返回一个0矩阵,因此行列式=0。我对编程相当陌生,所以我发现很难确切地说出原因,但我认为这与整个文件读取过程有关 该文件只是一个.data文件,矩阵元素存储在以空格分隔的列中,即: 1.71.20.5从文件中读取矩阵并计算行列式(C),c,matrix,C,Matrix,所以我写了一些代码,从一个文件中提取一个矩阵,把它放到一个数组中,然后计算它的行列式。但是,在运行时,数组似乎尚未填充,程序返回一个0矩阵,因此行列式=0。我对编程相当陌生,所以我发现很难确切地说出原因,但我认为这与整个文件读取过程有关 该文件只是一个.data文件,矩阵元素存储在以空格分隔的列中,即: 1.71.20.5 0.0-3.21.4 3.04.05.0 下面是(我认为是)代码的相关部分,不过如果有帮助的话,我可以发布整个内容 int main(int argc, char* argv
0.0-3.21.4
3.04.05.0 下面是(我认为是)代码的相关部分,不过如果有帮助的话,我可以发布整个内容
int main(int argc, char* argv[])
{
FILE *input;
int record, i, j;
int curr_col;
const int dim = DIMENSION;
double entries[dim][dim];
double tmp, determinant;
const char inp_fn[]="matrix.data";
/* Open file */
input = fopen(inp_fn, "r");
/* Check the pointer to file are not NULL */
if(input != (FILE*) NULL)
{
for(j=0; j<dim; j++, fopen(inp_fn, "r"))
{
record = 0; i = 0;
/* Read in records one by one and check the return value of fscanf */
while(fscanf(input,"%lf",&tmp) == 1)
{
curr_col = (record % dim);
if(curr_col==j)
{
/* Copy data points to the array */
entries[i][j] = (double)(tmp);
i++;
}
record++;
}
fclose(input);
}
}
else
printf("*** Could not open input or output file! ***\n");
/* Calculates determinant */
determinant = det(dim, entries);
printf("\nA = \n");
for(i=0; i<dim; i++)
{
for(j=0; j<dim; j++)
{
printf("%.1lf ", entries[i][j]);
}
printf("\n");
}
printf("\n");
printf("det(A) = %.3lf\n", determinant);
}
intmain(intargc,char*argv[])
{
文件*输入;
int记录,i,j;
国际货币;
const int dim=维度;
双条目[dim][dim];
双tmp,行列式;
const char inp_fn[]=“matrix.data”;
/*打开文件*/
输入=fopen(输入法,r);
/*检查指向文件的指针是否不为空*/
如果(输入!=(文件*)为空)
{
对于(j=0;j尝试使用peror(“fopen”);
在打开失败时打印错误,而不是使用printf
另外,请注意,每次在for循环中都会重新打开该文件
改变
for(j=0; j<dim; j++, fopen(inp_fn, "r"))
for(j=0; j<dim; j++, fopen(inp_fn, "r"))
用于(j=0;j脏补丁
从您的代码中,我看到了您每次读取不同列时都要打开文件的意图。这既低效又笨重。您可以通过更改以下内容使其工作(仅读取输入部分,我不知道代码的其余部分):
请注意,fopen
在进入if
条件之前只调用一次,所有内容都是一次性读取的
您可能还想在读取后添加一个检查,以确保记录==dim*dim
-以防提供的数据不够。很抱歉刚才看到了这一点,谢谢!不知道它存在。它说没有这样的文件或目录,但它肯定在那里…编辑:键入完整的目录,它现在正在工作,给我first列,但其余仍为0…:/仅在完成读取后调用fclose(input)
。您可以一次性将所有内容读取到数组中。因此,将fclose移到for循环之外?干杯!在我的矩阵中仍然只填充了一列:(非常出色!非常感谢,非常聪明–这是一种更有效的阅读方式:D
for(j=0; j<dim; j++, fopen(inp_fn, "r"))
for(j=0; j<dim; j++, input = fopen(inp_fn, "r"))
record = 0;
// Read the file at most (dim * dim) times to fill up the array
// The reading also stops when it cannot read any double number
while(fscanf(input,"%lf",&tmp) == 1 && record < dim * dim)
{
// Use some math to calculate the cell to put the new entry
entries[record / dim][record % dim] = tmp; // entries and tmp are double, no need for casting
record++;
}
// Close the file after done reading
fclose(input);