0

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

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

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

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

4

1 回答 1

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 
于 2013-11-02T18:49:06.577 回答