Pregunta

My professor gave us some code in class that will read in a matrix. However, it wont print out double values. If I have the following in a file

6.4 5.6 6.7
4.3 5.7 2.1
9.8 7.8 9.2

the code will round them down rather than printing out the actual double value. What needs to be changed? I have tried changing it to a double matrix, and printing it out using %g, etc.

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

float** readMatrix(int *nRows, int *nCols);

main() {
    //Holds our matrix of numbers  
    int nums[30][30];
    float** m;
    int r = 0, c = 0, i, j;


    m = (float**)readMatrix(&r, &c);

    for (i = 0; i < r; i++){
        for (j = 0; j < c; j++) printf("%1.0f ", m[i][j]);
        printf("\n");
    }
}

//Read a matrix from standard input
float** readMatrix(int *nRows, int *nCols) {
    int i = 0;
    int j = 0;
    int k = 0;
    char c;
    *nRows = 0; //The number of rows
    *nCols = 0; //The number of columns 
    int nums[30][30];
    char num[10];

    while (1) {

        //Read in the numbers on a row
        j = 0; // j = the index of the number on the row - start at zero
        while (1) {

            //We will re-use the index i, so set to zero
            i = 0;
            //Read characters from standard input until a space or EOL
            while ((c = getchar()) != ' ' && c != 10 && c != EOF) {
                num[i++] = c;
            }

            //Null terminate the array of characters
            num[i] = 0;

            //Changes the array of characters to a float
            nums[k][j++] = atof(num);

            //If we are at the end of the line or end of file - break
            if (c == 10 || c == EOF) break;

            //Set the number of numbers
            (*nCols) = j + 1;
        }

        //Stop if you are at the end of file
        if (c == EOF) break;

        //Go to the next row
        k++;

    } //End while(1) outer loop
    *nRows = k;

    //Allocate memory for the row pointers
    float** retMat = (float**)malloc((*nRows)*sizeof(float*));
    //Allocate memory for the rows themselves
    for (i = 0; i < (*nRows); i++) retMat[i] = (float*)malloc((*nCols)*sizeof(float));
    //Copy the nums matrix into the return matrix
    for (i = 0; i < (*nRows); i++) for (j = 0; j < (*nCols); j++) retMat[i][j] = nums[i][j];
    return retMat;

}
¿Fue útil?

Solución

You are first reading into nums array which is of type int. Change that to float.

nums[k][j++]=atof(num);

atof returns float which is rounded down to int.

------EDIT-----------

printf("%1.0f ", m[i][j]);

This is reason why it prints wrong now. Check it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top