用c语言编程求两个矩阵的乘积
时间: 2024-05-01 17:19:06 浏览: 153
以下是使用 C 语言编写的两个矩阵相乘的代码:
```c
#include <stdio.h>
int main()
{
int m, n, p, q, i, j, k;
printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &m, &n);
int first[m][n];
printf("Enter the elements of the first matrix:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &p, &q);
if (n != p)
{
printf("The matrices cannot be multiplied.");
return 0;
}
int second[p][q];
printf("Enter the elements of the second matrix:\n");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
scanf("%d", &second[i][j]);
}
}
int product[m][q];
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
product[i][j] = 0;
for (k = 0; k < n; k++)
{
product[i][j] += first[i][k] * second[k][j];
}
}
}
printf("The product of the two matrices is:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
printf("%d ", product[i][j]);
}
printf("\n");
}
return 0;
}
```
该程序首先要求用户输入两个矩阵的行数和列数,然后读取用户输入的矩阵元素。如果第一个矩阵的列数不等于第二个矩阵的行数,则程序输出错误消息并退出。如果两个矩阵可以相乘,则程序计算它们的乘积并将结果打印到屏幕上。
阅读全文
相关推荐


















