Reading a 3x3 Matrix from a file an then displayin

2019-08-31 07:03发布

问题:

I want to print the matrix but I don't know how.

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

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

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

if( (input != (FILE*) NULL) )
{
    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            fullmatrix[i][j] = input;
        }
        fscanf(input, "%f");

    }
    fclose(input);
    printf("%f %f %f\n %f %f %f\n %f %f %f\n", &matrix[i][j]);
}
else
    printf("Could not open file!\n");

return(0);
}

回答1:

for(i=0; i<3; i++)
{
    for(j=0; j<3; j++)
    {
        fullmatrix[i][j] = input;
    }
    fscanf(input, "%f");

}

should be:

for(i=0; i<3; i++) {
    for(j=0; j<3; j++) {
        fscanf(input, "%f", &fullmatrix[i][j]);
    }
}

and this line won't do what you think either:

printf("%f %f %f\n %f %f %f\n %f %f %f\n", &matrix[i][j]);

You need to print it one by one on your own using loops again:

for(i=0; i<3; i++) {
    for(j=0; j<3; j++) {
        printf("%f ", fullmatrix[i][j]);
    }
    printf("\n");
}


回答2:

For reading the file and putting it into the matrix and printing in one go:

for(i=0; i<3; i++) {
    for(j=0; j<3; j++) {
        fscanf(input, "%f", &fullmatrix[i][j]); // If you just want to print the matrix separately .. remove this line

        printf("%f ",matrix[i][j]);
    }
    printf("\n");
}