Перемножение двух матриц - C (СИ) (76858)
Формулировка задачи:
Для заданных матриц и найти
Программу на Си желательно с комментарием ... хочется понять и разобраться для усвоения материала..
Решение задачи: «Перемножение двух матриц»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
double **multiply_matrices(double **dest, size_t dest_rows, size_t dest_cols,
double **mat1, size_t mat1_rows, size_t mat1_cols,
double **mat2, size_t mat2_rows, size_t mat2_cols)
{
size_t i, j, k;
if(mat1_cols != mat2_rows ||
dest_rows != mat1_rows ||
dest_cols != mat2_cols)
return NULL;
for(i = 0; i < mat1_rows; ++i)
{
for(j = 0; j < mat2_cols; ++j)
{
double sum = 0;
for(k = 0; k < mat1_cols; ++k)
sum += mat1[i][k] * mat2[k][j];
dest[i][j] = sum;
}
}
return dest;
}
double **scale_matrix(double coeff,
double **dest, size_t dest_rows, size_t dest_cols,
double **mat, size_t mat_rows, size_t mat_cols)
{
size_t i, j;
if(dest_rows != mat_rows ||
dest_cols != mat_cols)
return NULL;
for(i = 0; i < dest_rows; ++i)
for(j = 0; j < mat_rows; ++j)
dest[i][j] = mat[i][j] * coeff;
return dest;
}
double **allocate_matrix(size_t rows, size_t cols)
{
size_t i;
double **matrix = malloc(rows * sizeof *matrix);
if(matrix == NULL)
return NULL;
for(i = 0; i < rows; ++i)
{
matrix[i] = malloc(cols * sizeof **matrix);
if(matrix[i] == NULL)
{
free(matrix);
return NULL;
}
}
return matrix;
}
int read_matrix(const char *prompt, double **matrix, size_t rows, size_t cols)
{
size_t i, j;
for(i = 0; i < rows; ++i)
{
for(j = 0; j < cols; ++j)
{
printf("%s", prompt);
fflush(stdout);
if(scanf("%lf", &matrix[i][j]) != 1)
return 0;
}
}
return 1;
}
void handle_error(const char *message)
{
fprintf(stderr, "ERROR: %s\n", message);
exit(EXIT_FAILURE);
}
void deallocate_matrix(double **matrix, size_t rows)
{
size_t i;
for(i = 0; i < rows; ++i)
free(matrix[i]);
free(matrix);
}
int main(void)
{
size_t n, i, j;
double **a, **b, **interm;
printf("Enter the order of square matrices: ");
fflush(stdout);
if(scanf("%u", &n) != 1)
handle_error(strerror(errno));
if((a = allocate_matrix(n, n)) == NULL ||
(b = allocate_matrix(n, n)) == NULL ||
(interm = allocate_matrix(n, n)) == NULL)
handle_error(strerror(errno));
puts("Enter the matrices A and B:");
if(read_matrix("A>>> ", a, n, n) == 0 ||
read_matrix("B>>> ", b, n, n) == 0)
handle_error(strerror(errno));
if(multiply_matrices(interm, n, n,
b, n, n,
b, n, n) == NULL)
handle_error("Nonconformant matrix dimensions");
if(multiply_matrices(b, n, n,
a, n, n,
interm, n, n) == NULL)
handle_error("Nonconformant matrix dimensions");
if(scale_matrix(.5, b, n, n, b, n, n) == NULL)
handle_error("Nonconformant matrix dimensions");
puts("Result:");
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
printf("%+8.3f", b[i][j]);
putchar('\n');
}
deallocate_matrix(a, n);
deallocate_matrix(b, n);
deallocate_matrix(interm, n);
exit(EXIT_SUCCESS);
}
Объяснение кода листинга программы
Этот код реализует функцию для перемножения двух матриц и функцию для масштабирования матрицы. Также в нём есть функции для чтения матрицы с консоли, для выделения памяти под матрицу и для освобождения памяти. В функции main создаются матрицы, заполняются их значениями, затем происходит перемножение матриц и масштабирование матрицы. Результат выводится на экран. Если при выполнении этих действий происходит ошибка, код выводит сообщение об ошибке и завершает работу.