gpt4 book ai didi

c - 读取和打印矩阵 C

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:42 24 4
gpt4 key购买 nike

我的作业是从文件中读取数字以形成矩阵。每行的前两个整数是行和列,后面的整数是矩阵中的数据。

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

在我的 main 函数中,我有两个矩阵 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);

输入看起来像:

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

关于c - 读取和打印矩阵 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com