Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- typedef struct matrix {
- float ** data;
- int stroke;
- int colum;
- } matrix;
- typedef struct mult {
- matrix A;
- matrix B;
- matrix C;
- } mult;
- void memory(mult *c)
- {
- c->C.stroke = c->A.stroke;
- c->C.colum = c->B.colum;
- c->A.data = (float**)malloc(c->A.stroke * sizeof(matrix));
- c->B.data = (float**)malloc(c->B.stroke * sizeof(matrix));
- c->C.data = (float**)malloc(c->C.stroke * sizeof(matrix));
- for (int i = 0; i < c->A.stroke; i++)
- {
- c->A.data[i] = (float*)malloc(c->A.colum * sizeof(matrix));
- c->C.data[i] = (float*)malloc(c->C.colum * sizeof(matrix));
- }
- for (int i = 0; i < c->B.stroke; i++)
- {
- c->B.data[i] = (float*)malloc(c->B.colum * sizeof(matrix));
- }
- }
- int read(mult *c)
- {
- printf_s("Matrix A(n x k): ");
- scanf_s("%d %d", &c->A.stroke, &c->A.colum);
- printf_s("Matrix B(k x m): ");
- scanf_s("%d %d", &c->B.stroke, &c->B.colum);
- if (c->B.stroke != c->A.colum) { printf_s("Can't multiply!"); return 1; }
- memory(c);
- printf_s("Matrix A\n");
- for (int i = 0; i < c->A.stroke; i++)
- {
- printf_s("S%d: ", i);
- for (int j = 0; j < c->A.colum; j++) { scanf_s("%f", &c->A.data[i][j]); }
- }
- printf_s("Matrix B\n");
- for (int i = 0; i < c->B.stroke; i++)
- {
- printf_s("S%d: ", i);
- for (int j = 0; j < c->B.colum; j++) { scanf_s("%f", &c->B.data[i][j]); }
- }
- for (int i = 0; i < c->C.stroke; i++)
- {
- for (int j = 0; j < c->C.colum; j++) { c->C.data[i][j] = 0; }
- }
- return 0;
- }
- void multiply(mult *c)
- {
- for (int i = 0; i < c->C.stroke; i++)
- {
- for (int j = 0; j < c->C.colum; j++)
- {
- for (int k = 0; k < c->A.colum; k++) { c->C.data[i][j] += c->A.data[i][k] * c->B.data[k][j]; }
- }
- }
- }
- void output(mult *c)
- {
- printf_s("Matrix C(n x m): \n");
- for (int i = 0; i < c->C.stroke; i++)
- {
- for (int j = 0; j < c->C.colum; j++) { printf_s("%.1f ", c->C.data[i][j]); }
- printf_s("\n");
- }
- }
- void memory_free(mult *c)
- {
- for (int i = 0; i < c->B.stroke; i++) { free(c->B.data[i]); }
- for (int i = 0; i < c->A.stroke; i++)
- {
- free(c->A.data[i]);
- free(c->C.data[i]);
- }
- free(c->A.data);
- free(c->B.data);
- free(c->C.data);
- free(c);
- }
- int main()
- {
- mult *c = (mult*)malloc(sizeof(mult));
- if (read(c)) {
- _getch();
- return 0; }
- multiply(c);
- output(c);
- memory_free(c);
- _getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement