用C语言写一个两个矩阵相乘的代码
时间: 2024-05-27 20:14:18 浏览: 196
#include <stdio.h>
int main() {
int m, n, p, q, i, j, k;
printf("Enter the number of rows and columns for the first matrix: ");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d%d", &p, &q);
if(n!=p) {
printf("Matrices cannot be multiplied!");
return 0;
}
int mat1[m][n], mat2[p][q], prod[m][q];
printf("\nEnter the elements of the first matrix:\n");
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
scanf("%d", &mat1[i][j]);
}
}
printf("\nEnter the elements of the second matrix:\n");
for(i=0; i<p; i++) {
for(j=0; j<q; j++) {
scanf("%d", &mat2[i][j]);
}
}
for(i=0; i<m; i++) {
for(j=0; j<q; j++) {
prod[i][j] = 0;
for(k=0; k<n; k++) {
prod[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
printf("\nProduct of the matrices:\n");
for(i=0; i<m; i++) {
for(j=0; j<q; j++) {
printf("%d ", prod[i][j]);
}
printf("\n");
}
return 0;
}
阅读全文