我的教授给了我们一些将在矩阵中读取的代码。但是,它不会打印出双值。如果我在文件中有以下内容
6.4 5.6 6.7
4.3 5.7 2.1
9.8 7.8 9.2
代码会将它们向下舍入而不是打印出实际的double值。需要改变什么?我已经尝试将其更改为双矩阵,并使用%g等打印出来
#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;
}
答案 0 :(得分:1)
您首先阅读的nums
数组int
类型。将其更改为float
。
nums[k][j++]=atof(num);
atof
返回float
,向下舍入为int
。
------ EDIT -----------
printf("%1.0f ", m[i][j]);
这就是为什么它现在打印错误的原因。检查一下。