gpt4 book ai didi

c - 从文件中读取矩阵并计算行列式(C 语言)

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:26 25 4
gpt4 key购买 nike

所以我编写了一些代码来从文件中获取矩阵,将其放入数组中并计算其行列式。然而,在运行时,数组似乎没有被填充,程序返回一个 0 矩阵,因此行列式 = 0。我是编程的新手,所以我发现很难确切地确定原因,但我认为这是某种原因处理整个从文件读取的过程。

该文件只是一个 .data 文件,矩阵元素存储在以空格分隔的列中,即:

1.7 1.2 0.5
0.0 -3.2 1.4
3.0 4.0 5.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);

}

我得到“无法打开输入或输出文件!”运行程序时出现错误和一个空矩阵...求助!?

最佳答案

脏修复

从您的代码中,我看到您打算在每次阅读不同的专栏时打开文件。它效率低下且笨重。您可以通过更改使其工作(仅阅读输入部分,我不知道您的其余代码):

for(j=0; j<dim; j++, fopen(inp_fn, "r"))

for(j=0; j<dim; j++, input = fopen(inp_fn, "r"))

您当前的代码将打开文件并浪费资源,而 fclose 将遇到错误,因为 input 中的文件已在上一次迭代中关闭。

我上面建议的代码会将新的 FILE*fopen 分配给 input

当然,上面的方式是非常低效的,正如我在开头所指出的。


更好的方法

更好的方法是在 if 语句 if(input != (FILE*) NULL) 中(使用 j 移除循环):

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

请注意,fopen 在进入if 条件之前只被调用一次,所有内容都是一次性读取的。

您可能还想在阅读后添加一个检查以确保 record == dim * dim - 以防万一提供的数据不够。

关于c - 从文件中读取矩阵并计算行列式(C 语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13504777/

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