所以我找到一个未知矩阵中的行数,然后想使用这个数字来扫描矩阵正确的次数并在最后显示矩阵。我需要找到维度,因为我想继续找到行列式,但这是迄今为止我的代码。
无论如何,问题是“暗淡”整数似乎没有传输,因为它打印出了一堆疯狂的数字
#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/