Data_Structure/作業/老師解答/unit1/matrix-product-file-v0.cpp
2025-01-20 21:25:33 +08:00

78 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Program: matrix-product-file-v0.c (Report comments/bugs to chikh@yuntech.edu.tw)
Function: 讀取檔案設定矩陣元素設置好A與B矩陣之後實作矩陣相乘
Note: 預設讀取matrixData1.txtmatrixData2.txt用於測試A與B維度不符的狀況
*/
#include <stdio.h>
#define N 100
int rowA, colA, rowB, colB;
char idA, idB;
int init(int A[][N], int B[][N]) //初始化A與B矩陣
{
FILE *f;
int i, j;
f = fopen("matrixData1.txt","r");
//f = fopen("matrixData2.txt","r");
fscanf(f,"%c %d %d %c %d %d",&idA,&rowA,&colA,&idB,&rowB,&colB);
if (colA != rowB) return 0;
for (i = 0; i < rowA; i++)
for (j = 0; j < colA; j++)
fscanf(f,"%d",&A[i][j]);
for (i = 0; i < rowB; i++)
for (j = 0; j < colB; j++)
fscanf(f,"%d",&B[i][j]);
return 1;
}
void mul(int A[][N], int B[][N], int C[][N]) //實作C=A*B矩陣相乘運算運算結果存入C
{
int i, j, k, sum;
for (i = 0; i < rowA; i++) {
for (j = 0; j < colB; j++) {
for (sum = k = 0; k < colA; k++)
sum += A[i][k]*B[k][j];
C[i][j] = sum;
}
}
}
void show(char p, char q, int X[][N], int row, int col)
{
int i, j;
if (q != '-') //以q來區隔顯示模式的差異
printf("\nMatrix %c*%c =\n",p,q);
else
printf("\nMatrix %c =\n",p);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) printf("%6d",X[i][j]);
printf("\n");
}
printf("\n");
}
int main()
{
int A[N][N] = {0}, B[N][N] = {0}, C[N][N] = {0}, D[N][N] = {0};
printf("\n*** 讀取描述矩陣的檔案,進行矩陣乘積運算 ***\n\n");
if (init(A,B)==0) {
printf("矩陣維度有誤無法運算sorry\n");
return -1;
}
mul(A,B,C);
show('A','-',A,rowA,colA);
show('B','-',B,rowB,colB);
show('A','B',C,rowA,colB);
return 0;
}