C语言教程-矩阵乘法在C语言中的实现

矩阵乘法是在C语言中实现矩阵相乘的过程。我们可以对两个矩阵进行加法、减法、乘法和除法。为此,我们从用户那里获取行数、列数、第一个矩阵元素和第二个矩阵元素的输入。然后我们对用户输入的矩阵进行乘法运算。
在矩阵乘法中,第一个矩阵的一行元素与第二个矩阵的所有列元素相乘。
让我们看看在C语言中实现矩阵乘法的程序:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a[10][10], b[10][10], mul[10][10];
int r, c, i, j, k;
system("cls");
printf("Enter the number of rows: ");
scanf("%d", &r);
printf("Enter the number of columns: ");
scanf("%d", &c);
printf("Enter the elements of the first matrix:\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of the second matrix:\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
scanf("%d", &b[i][j]);
}
}
printf("Multiplication of the matrices:\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
mul[i][j] = 0;
for (k = 0; k < c; k++) {
mul[i][j] += a[i][k] * b[k][j];
}
}
}
// Printing the result
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf("%d\t", mul[i][j]);
}
printf("\n");
}
return 0;
}
输出:
Enter the number of rows: 3
Enter the number of columns: 3
Enter the elements of the first matrix:
1 1 1
2 2 2
3 3 3
Enter the elements of the second matrix:
1 1 1
2 2 2
3 3 3
Multiplication of the matrices:
6 6 6
12 12 12
18 18 18