110 lines
2.5 KiB
C
110 lines
2.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <ctype.h>
|
|
|
|
#define MAX_SIZE 10 /* 定義矩陣的最大大小 */
|
|
|
|
/* 函數:讀取矩陣 */
|
|
int readMatrix(int matrix[MAX_SIZE][MAX_SIZE], int *cols, FILE *file) {
|
|
int i = 0, j = 0, temp;
|
|
char ch;
|
|
|
|
while (fscanf(file, "%d", &temp) == 1) {
|
|
matrix[i][j] = temp;
|
|
j++;
|
|
|
|
/* 檢查當前行是否結束 */
|
|
ch = fgetc(file);
|
|
if (ch == '\n') {
|
|
if (i == 0) {
|
|
*cols = j; // 紀錄第一行的列數
|
|
}
|
|
i++; /* 移到下一行 */
|
|
j = 0; /* 重置列計數 */
|
|
}
|
|
if (ch == EOF) break;
|
|
}
|
|
return i; /* 返回行數 */
|
|
}
|
|
|
|
/* 函數:跳過空行 */
|
|
void skipEmptyLines(FILE *file) {
|
|
char ch;
|
|
while ((ch = fgetc(file)) != EOF) {
|
|
if (!isspace(ch) || ch == '\n') {
|
|
ungetc(ch, file); // 將非空白字符退回流,準備下一次讀取
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* 函數:印出矩陣 */
|
|
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols) {
|
|
int i, j;
|
|
for (i = 0; i < rows; i++) {
|
|
for (j = 0; j < cols; j++) {
|
|
printf("%d ", matrix[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
}
|
|
|
|
/* 函數:矩陣乘法 */
|
|
void multiplyMatrix(int a[MAX_SIZE][MAX_SIZE], int b[MAX_SIZE][MAX_SIZE], int c[MAX_SIZE][MAX_SIZE],
|
|
int rowsA, int colsA, int colsB) {
|
|
int i, j, k;
|
|
for (i = 0; i < rowsA; i++) {
|
|
for (j = 0; j < colsB; j++) {
|
|
c[i][j] = 0;
|
|
for (k = 0; k < colsA; k++) {
|
|
c[i][j] += a[i][k] * b[k][j];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
FILE *file;
|
|
int matrixA[MAX_SIZE][MAX_SIZE] = {0}, matrixB[MAX_SIZE][MAX_SIZE] = {0}, result[MAX_SIZE][MAX_SIZE] = {0};
|
|
int rowsA = 0, colsA = 0, rowsB = 0, colsB = 0;
|
|
|
|
/* 開啟檔案 */
|
|
file = fopen("matrix_input.txt", "r");
|
|
if (file == NULL) {
|
|
printf("無法開啟檔案\n");
|
|
return 1;
|
|
}
|
|
|
|
/* 讀取矩陣 A */
|
|
rowsA = readMatrix(matrixA, &colsA, file);
|
|
|
|
/* 跳過空行 */
|
|
skipEmptyLines(file);
|
|
|
|
/* 讀取矩陣 B */
|
|
rowsB = readMatrix(matrixB, &colsB, file);
|
|
|
|
/* 關閉檔案 */
|
|
fclose(file);
|
|
|
|
/* 印出矩陣大小 */
|
|
printf("矩陣 A: %d x %d\n", rowsA, colsA);
|
|
printf("矩陣 B: %d x %d\n", rowsB, colsB);
|
|
|
|
/* 檢查矩陣是否可以相乘 */
|
|
if (colsA != rowsB) {
|
|
printf("錯誤:這兩個矩陣無法相乘\n");
|
|
return 1;
|
|
}
|
|
|
|
/* 執行矩陣乘法 */
|
|
multiplyMatrix(matrixA, matrixB, result, rowsA, colsA, colsB);
|
|
|
|
/* 印出結果 */
|
|
printf("矩陣乘法結果:\n");
|
|
printMatrix(result, rowsA, colsB);
|
|
|
|
return 0;
|
|
}
|
|
|