c - 未正确读取矩阵

标签 c matrix

好吧,我的任务是创建一个程序,从文件中读取未知矩阵,然后以某种方式计算它的行​​列式。我几乎完成了所有工作,只是从文件中获取数字后数字似乎乱七八糟。

如果你只看我的代码可能会更容易,这是直到刚读完矩阵的部分,我说的值都是乱七八糟的

#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 < dimj < dim .

数组的索引以 0 开头,而不是 1。

关于c - 未正确读取矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749790/

相关文章:

matrix - 基本高斯消除求解器产生错误结果

php - 基于对象的父=>子关系构建访问矩阵?

c - 长时间阅读后出现段错误

c - 堆栈如何使用外部函数接口(interface) (FFI)?

c - 如何测试结构释放

矩阵旋转的c++程序

c - 定义字符串数组

c - 调整哈希 C 大小时发生内存泄漏

javascript - 浏览器 JavaScript 是否允许 SIMD 或矢量化操作?

python - 修改矩阵。 python 非常有趣的任务