#include #include #include 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]; } } } } void read_matrix(FILE *file, int **a, int rows, int cols) { char line[1000]; char *token; int i, j; for (i = 0; i < rows; i++) { fgets(line, sizeof(line), file); token = strtok(line, " \n"); for (j = 0; j < cols; j++) { a[i][j] = atoi(token); token = strtok(NULL, " \n"); } } } int get_matrix_dimensions(FILE *file, int *m, int *k, int *n) { char line[1000]; int rows1 = 0, cols1 = 0, rows2 = 0, cols2 = 0; int first_matrix = 1; int cols; char *token; while (fgets(line, sizeof(line), file)) { if (strlen(line) <= 1) { first_matrix = 0; continue; } token = strtok(line, " \n"); cols = 0; while (token != NULL) { cols++; token = strtok(NULL, " \n"); } if (first_matrix) { cols1 = cols; rows1++; } else { cols2 = cols; rows2++; } } *m = rows1; *k = cols1; *n = cols2; if (cols1 != rows2) { printf("錯誤!矩陣無法相乘\n"); printf("k1=%d, k2=%d\n",cols1,rows2); return 1; } return 0; } int main() { FILE *file; int m, k, n, i, j; if ((file = fopen("matrix_input.txt", "r")) == NULL) { printf("錯誤!無法打開文件\n"); return 1; } if (get_matrix_dimensions(file, &m, &k, &n)) { fclose(file); return 1; } printf("第一個矩陣:%d 行 %d 列\n", m, k); printf("第二個矩陣:%d 行 %d 列\n", k, n); int **arr_a = (int**)malloc(m * sizeof(int*)); int **arr_b = (int**)malloc(k * sizeof(int*)); int **arr_c = (int**)malloc(m * sizeof(int*)); for (i = 0; i < m; i++) { arr_a[i] = (int*)malloc(k * sizeof(int)); arr_c[i] = (int*)malloc(n * sizeof(int)); } for (i = 0; i < k; i++) { arr_b[i] = (int*)malloc(n * sizeof(int)); } //回到文件的開始 rewind(file); read_matrix(file, arr_a, m, k); /* 跳過矩陣之間的空行 */ char line[1000]; fgets(line, sizeof(line), file); read_matrix(file, arr_b, k, n); mul(arr_a, arr_b, arr_c, m, k, n); printf("結果矩陣:\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d ", arr_c[i][j]); } printf("\n"); } fclose(file); free(arr_a); free(arr_b); free(arr_c); for (i = 0; i < m; i++) { free(arr_a[i]); free(arr_c[i]); } for (i = 0; i < k; i++) { free(arr_b[i]); } return 0; }