[英]Reading and Printing a Matrix C
我有一項任務,要從文件中讀取數字以形成矩陣。 每行的前兩個整數是行和列,然后其余的整數是矩陣中的數據。
2 2 1 2 3 4
看起來像
1 2
3 4
我能夠使用以下命令成功加載一個矩陣中:
void RdMatrix(FILE *file, int (*matrix)[MAXSIZE][MAXSIZE], int *row, int *column)
{
int data;
int matRow = RdRowSize(file);
int matCol = RdColumnSize(file);
*row = matRow;
*column = matCol;
int i, j;
for (i = 0; i < matRow; i++)
{
for (j = 0; j < matCol; j++)
{
fscanf(file, "%d", &data);
*matrix[i][j] = data;
}
}
然后我可以用
void PrMat(int(*matrix)[MAXSIZE][MAXSIZE], int row, int col)
{
int i, j;
printf("\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d ", *matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
在我的主要函數中,我有兩個矩陣A[MAXSIZE][MAXSIZE]
和B[MAXSIZE][MAXSIZE]
, rowA = 0, colA = 0;
並且rowB = 0, colB = 0;
。 我叫RdMatrix(fpin, &A, &rowA, &columnA); RdMatrix(fpin, &B, &rowB, &columnB); PrMat(&A, rowA, columnA);
RdMatrix(fpin, &A, &rowA, &columnA); RdMatrix(fpin, &B, &rowB, &columnB); PrMat(&A, rowA, columnA);
輸入看起來像:
2 2 1 2 3 4
2 2 9 8 7 6
然后打印
1 2
9 8
9 8
7 6
什么時候應該打印
1 2
3 4
9 8
7 6
我不允許使用任何庫,也無濟於事,因為稍后我必須在匯編中重新編寫該庫。
編輯:包括代碼
#include <stdio.h>
#define MAXSIZE 10
FILE *fpin;
int RdRowSize(FILE *file)
{
int row;
fscanf(file, "%d", &row);
return row;
}
int RdColumnSize(FILE *file)
{
int col;
fscanf(file, "%d", &col);
return col;
}
void RdMatrix(FILE *file, int (*matrix)[MAXSIZE][MAXSIZE], int *row, int *column)
{
int data;
int matRow = RdRowSize(file);
int matCol = RdColumnSize(file);
*row = matRow;
*column = matCol;
int i, j;
printf("\n=====================\nLoading Matrix\n=====================\n");
for (i = 0; i < matRow; i++)
{
for (j = 0; j < matCol; j++)
{
fscanf(file, "%d", &data);
*matrix[i][j] = data;
}
}
}
void PrMat(int(*matrix)[MAXSIZE][MAXSIZE], int row, int col)
{
int i, j;
printf("\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d ", *matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
int main(void)
{
int RsizeM, CsizeM; /*matrix row size and column size*/
int A[MAXSIZE][MAXSIZE], B[MAXSIZE][MAXSIZE]; /*the two matrices*/
int rowA=0, columnA=0, rowB=0, columnB=0; /* the row and column sizes of A and B */
/*open input file - file name is hardcoded*/
fpin = fopen("INA1.txt", "r"); /* open the file for reading */
if (fpin == NULL)
{
fprintf(stdout, "Cannot open input file - Bye\n");
return(-1); /* if problem, exit program*/
}
/*ASSUMPTIONS: the file is not empty and contains has at least 1 set of matrices*/
/* Add while loop after testing a single iteration */
RdMatrix(fpin, &A, &rowA, &columnA);
RdMatrix(fpin, &B, &rowB, &columnB);
PrMat(&A, rowA, columnA);
PrMat(&B, rowA, columnB);
fclose(fpin); /* close the file */
return (0);
}
然后它必須打開的文件稱為INA1.txt
引用元素時,應使用(*matrix)[i][j]
而不是*matrix[i][j]
。 另外,在打印B矩陣時,它應該是rowB
,而不是rowA
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.