Data_Structure/作業/unit1/matrix multiplication/test3.c

138 lines
2.9 KiB
C
Raw Normal View History

2025-01-20 21:25:33 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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("<EFBFBD><EFBFBD><EFBFBD>~!<21>x<EFBFBD>}<7D>L<EFBFBD>k<EFBFBD>ۭ<EFBFBD>\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("<EFBFBD><EFBFBD><EFBFBD>~!<21>L<EFBFBD>k<EFBFBD><6B><EFBFBD>}<7D><><EFBFBD><EFBFBD>\n");
return 1;
}
if (get_matrix_dimensions(file, &m, &k, &n)) {
fclose(file);
return 1;
}
printf("<EFBFBD>Ĥ@<40>ӯx<D3AF>}<7D>G%d <20><> %d <20>C\n", m, k);
printf("<EFBFBD>ĤG<EFBFBD>ӯx<EFBFBD>}<7D>G%d <20><> %d <20>C\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));
}
//<2F>^<5E><><EFBFBD><EFBFBD><EFBFBD>󪺶}<7D>l
rewind(file);
read_matrix(file, arr_a, m, k);
/* <20><><EFBFBD>L<EFBFBD>x<EFBFBD>}<7D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŧ<EFBFBD> */
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);
2025-01-20 21:30:53 +08:00
printf("<EFBFBD><EFBFBD><EFBFBD>G<EFBFBD>x<EFBFBD>}<7D>G\n");
2025-01-20 21:25:33 +08:00
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]);
}
2025-01-20 21:30:53 +08:00
2025-01-20 21:25:33 +08:00
return 0;
}