如何用c语言实现矩阵乘法
时间: 2023-11-27 22:05:05 浏览: 29
矩阵乘法可以用C语言实现,具体实现方法可以参考以下示例代码:
``` c
#include <stdio.h>
const int MAX = 100;
int main()
{
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
int n, m, p, q, i, j, k;
printf("Enter the order of Matrix A:\n");
scanf("%d %d", &n, &m);
printf("Enter the elements of Matrix A:\n");
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
scanf("%d", &a[i][j]);
printf("Enter the order of Matrix B:\n");
scanf("%d %d", &p, &q);
if (m != p) {
printf("Error: Matrices cannot be multiplied\n");
return 0;
}
printf("Enter the elements of Matrix B:\n");
for(i = 0; i < p; i++)
for(j = 0; j < q; j++)
scanf("%d", &b[i][j]);
for(i = 0; i < n; i++)
for(j = 0; j < q; j++)
c[i][j] = 0;
for(i = 0; i < n; i++)
for(j = 0; j < q; j++)
for(k = 0; k < m; k++)
c[i][j] += a[i][k] * b[k][j];
printf("Product of matrices A & B is:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < q; j++)
printf("%d ", c[i][j]);
printf("\n");
}
return 0;
}
```
这个程序定义了3个二维数组a、b、c,分别存放输入的两个矩阵和它们的积。首先,程序会询问用户输入矩阵A的行列数和元素,再输入矩阵B的行列数和元素。接下来,程序会检查两个矩阵是否能相乘,如果不能,就输出错误信息并退出程序。否则,程序会计算两个矩阵的乘积,并存放到数组c中。最后,程序会输出数组c中的元素,即矩阵A和B的乘积。
希望这个示例代码可以帮助您实现矩阵乘法。