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

109 lines
2.5 KiB
C++
Raw Permalink 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-v1.c (Report comments/bugs to chikh@yuntech.edu.tw)
Function: 從檔案讀入矩陣元素,並依所需維度配置記憶體空間、儲存矩陣內容,再進行乘法運算
Notes:
1) 輸入可為 matrixData1.txt、matrixData2.txt、matrixData3.txt 或 matrixData4.txt
2) 動態配置二維陣列的方式可參見第四單元的複習「C語言指標與字串」所載PPT檔案第64--68頁
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row, col;
int **data; /* 將用於表示二維陣列 */
} matrix;
int **readElements(FILE *filePtr, int row, int col)
{
int **data = (int**)malloc(row*sizeof(int*));
int i, j, value;
for (i = 0; i < row; i++) {
data[i] = (int*)malloc(col*sizeof(int));
for (j = 0; j < col; j++) {
fscanf(filePtr," %d",&value);
data[i][j] = value;
}
}
return data;
}
int init(FILE *f, char *idA, matrix *A, char *idB, matrix *B) //初始化A與B矩陣
{
fscanf(f," %c %d %d %c %d %d",idA,&A->row,&A->col,idB,&B->row,&B->col);
A->data = readElements(f,A->row,A->col);
B->data = readElements(f,B->row,B->col);
return 0;
}
int multiply(FILE *f, matrix *A, matrix *B, matrix *C)
{
int i, j, k, sum;
if (A->col != B->row) {
printf("矩陣維度不相符,無法運算!");
return -1;
}
printf("乘積結果C_%dx%d\n",A->row,B->col);
fprintf(f,"\n--- Output ---\nC_%dx%d\n",A->row,B->col);
C->data = (int**)malloc(A->row*sizeof(int*));
for (i = 0; i < A->row; i++) {
C->data[i] = (int*)malloc(B->col*sizeof(int));
for (j = 0; j < B->col; j++) {
for (k = sum = 0; k < A->col; k++)
sum += (A->data[i][k] * B->data[k][j]);
C->data[i][j] = sum;
printf("%d\t",C->data[i][j]);
fprintf(f,"%d\t",C->data[i][j]);
}
printf("\n");
fprintf(f,"\n");
}
C->row = A->row;
C->col = B->col;
return 0;
}
void show(char id, matrix *m)
{
int i, j;
printf("%c_%dx%d = \n",id,m->row,m->col);
for (i = 0; i < m->row; i++) {
for (j = 0; j < m->col; j++)
printf("%d\t",m->data[i][j]);
printf("\n");
}
printf("\n");
}
int main()
{
char fileName[20], idA, idB;
matrix A, B, C;
FILE *f;
printf("*** 矩陣相乘運算程式 ***\n\n輸入檔名 ==> ");
scanf("%s",fileName);
if ((f = fopen(fileName,"r+")) == NULL) {
printf("\a%s檔案不存在\n",fileName);
return 1;
}
init(f,&idA,&A,&idB,&B);
show(idA,&A);
show(idB,&B);
freopen(fileName,"a+",f); //重新開檔,將以附加(append)模式新增資料,避免檔案原有的資料被覆寫掉
multiply(f,&A,&B,&C); //執行乘法運算過程中,將把結果顯示於螢幕並儲存於檔案中
fclose(f);
return 0;
}