c - 在我的代码中转移号码

标签 c matrix numbers transfer

所以我找到一个未知矩阵中的行数,然后想使用这个数字来扫描矩阵正确的次数并在最后显示矩阵。我需要找到维度,因为我想继续找到行列式,但这是迄今为止我的代码。

无论如何,问题是“暗淡”整数似乎没有传输,因为它打印出了一堆疯狂的数字

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main(int argc, char* argv[])
{
    FILE       *input;
    int        i, j, temp, dim;  
    float      fullmatrix[dim][dim];
    const char inp_fn[]="matrix.dat";

/*Open File*/
input = fopen(inp_fn, "r");
dim = 0;

while (EOF != (temp = fgetc(input)))
{
    if (temp=='\n')
    {
        ++dim;
    }
}

if( (input != (FILE*) NULL) )
{
    for(i=0; i<=dim; i++)
    {
        for(j=0; j<=dim; j++)
        {
            fscanf(input, "%f", &fullmatrix[i][j]);
            printf("%f ", fullmatrix[i][j]);
        }
        printf("\n");
    }
    fclose(input);
}
else
{
    printf("Could not open file!\n");
}

return(0);
}

我对此很陌生,所以我可能很愚蠢。

最佳答案

我发现这段代码可以工作...但是请阅读注释 \\ 并注意可变长度数组 (VLA) 上的注释。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main(int argc, char* argv[])
{
    FILE       *input;
    int        i, j, temp, dim;  

    const char inp_fn[]="matrix.dat";

/*Open File*/
input = fopen(inp_fn, "r");
dim = 0;

while (EOF != (temp = fgetc(input)))
{
    if (temp=='\n')
    {
        ++dim;
    }
}

float fullmatrix[dim][dim];  // define fullmatrix after dim is known

// we close and reopen the file. We could also move back to the beginning of the file.
fclose(input);

printf("%d\n", dim);

input = fopen(inp_fn, "r");

// Probably not the safest way...we just assume that the file has not change after we 
// determined dim
for (i=0; i<dim; i++) 
 {  
    for(j=0; j<dim; j++)
    {
       fscanf(input, "%f", &fullmatrix[i][j]);
        printf("%f ", fullmatrix[i][j]);
    }
    printf("\n");
}

fclose(input);


return(0);
}

示例输出:

3
1.000000 2.000000 3.000000 
4.000000 5.000000 6.000000 
7.000000 8.000000 9.000000 

关于c - 在我的代码中转移号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19744983/

相关文章:

通过mmap分配的内存是否可以覆盖数据段

c - 如何将程序拆分为多个包含一个 .h 和几个 .c 文件的文件?

用 R 中的前一行替换 NA 行

android - 如何设置图像矩阵的位置?

matrix - 在 ARKit 中将屏幕点取消投影到水平面

c - GCC 中如何实现精确宽度的整数类型?

c - int **p 的奇怪行为?

javascript - 将 JavaScript 中的数学语句中的数字更改为带分隔符的数字

java - 两个随机数发生器(发牌)

vb.net - VB NET 中最快的排列代码排列数字