129 lines
2.6 KiB
C
129 lines
2.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define MAX_LINE_LENGTH 1000
|
|
|
|
// 分配矩陣記憶體
|
|
int** allocateMatrix(int rows, int cols) {
|
|
int i;
|
|
int** matrix = (int**)malloc(rows * sizeof(int*));
|
|
for (i = 0; i < rows; i++) {
|
|
matrix[i] = (int*)malloc(cols * sizeof(int));
|
|
}
|
|
return matrix;
|
|
}
|
|
|
|
// 釋放矩陣記憶體
|
|
void freeMatrix(int** matrix, int rows) {
|
|
int i ;
|
|
for (i = 0; i < rows; i++) {
|
|
free(matrix[i]);
|
|
}
|
|
free(matrix);
|
|
}
|
|
|
|
// 矩陣乘法
|
|
void mul(int **a, int **b, int **c, int m, int k, int n) {
|
|
int i , j , l ;
|
|
for (i = 0; i < m; i++) {
|
|
for (j = 0; j < n; j++) {
|
|
c[i][j] = 0;
|
|
for (l = 0; l < k; l++) {
|
|
c[i][j] += a[i][l] * b[l][j];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 讀取矩陣並返回維度
|
|
int** readMatrix(FILE* file, int* rows, int* cols) {
|
|
char line[MAX_LINE_LENGTH];
|
|
int** matrix = NULL;
|
|
*rows = 0;
|
|
*cols = 0;
|
|
|
|
while (fgets(line, sizeof(line), file)) {
|
|
if (strlen(line) <= 1) break; // 空行表示矩陣結束
|
|
|
|
(*rows)++;
|
|
int tempCols = 0;
|
|
char* token = strtok(line, " \t\n");
|
|
|
|
while (token != NULL) {
|
|
tempCols++;
|
|
token = strtok(NULL, " \t\n");
|
|
}
|
|
|
|
if (*cols == 0) {
|
|
*cols = tempCols;
|
|
matrix = allocateMatrix(*rows, *cols);
|
|
}
|
|
|
|
if (tempCols != *cols) {
|
|
printf("錯誤:矩陣列數不一致\n");
|
|
exit(1);
|
|
}
|
|
|
|
// 重新讀取該行並存儲數據
|
|
int col = 0;
|
|
token = strtok(line, " \t\n");
|
|
while (token != NULL) {
|
|
matrix[*rows - 1][col++] = atoi(token);
|
|
token = strtok(NULL, " \t\n");
|
|
}
|
|
}
|
|
|
|
return matrix;
|
|
}
|
|
|
|
int main() {
|
|
int i , j ;
|
|
FILE *file = fopen("matrix_input.txt", "r");
|
|
if (file == NULL) {
|
|
printf("無法開啟檔案\n");
|
|
return 1;
|
|
}
|
|
|
|
int m, k1, k2, n;
|
|
int **arr_a, **arr_b, **arr_c;
|
|
|
|
// 讀取第一個矩陣
|
|
arr_a = readMatrix(file, &m, &k1);
|
|
|
|
// 讀取第二個矩陣
|
|
arr_b = readMatrix(file, &k2, &n);
|
|
|
|
fclose(file);
|
|
|
|
// 檢查矩陣是否可以相乘
|
|
if (k1 != k2) {
|
|
printf("錯誤:這兩個矩陣無法相乘\n");
|
|
freeMatrix(arr_a, m);
|
|
freeMatrix(arr_b, k2);
|
|
return 1;
|
|
}
|
|
|
|
// 分配結果矩陣的空間
|
|
arr_c = allocateMatrix(m, n);
|
|
|
|
// 執行矩陣乘法
|
|
mul(arr_a, arr_b, arr_c, m, k1, n);
|
|
|
|
// 輸出結果
|
|
printf("矩陣乘法結果:\n");
|
|
for (i = 0; i < m; i++) {
|
|
for (j = 0; j < n; j++) {
|
|
printf("%d ", arr_c[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
// 釋放記憶體
|
|
freeMatrix(arr_a, m);
|
|
freeMatrix(arr_b, k1);
|
|
freeMatrix(arr_c, m);
|
|
|
|
return 0;
|
|
}
|