任意输入两个矩阵,计算并输出两个矩阵的乘积矩阵用c程序怎么写
时间: 2023-09-16 16:12:13 浏览: 175
可以使用双重循环实现矩阵的乘积,具体代码如下:
```c
#include <stdio.h>
int main() {
int row1, col1, row2, col2;
printf("Enter the dimensions of the first matrix: ");
scanf("%d %d", &row1, &col1);
printf("Enter the dimensions of the second matrix: ");
scanf("%d %d", &row2, &col2);
// Check if matrices can be multiplied
if (col1 != row2) {
printf("Matrices cannot be multiplied!\n");
return 0;
}
int mat1[row1][col1], mat2[row2][col2], prod[row1][col2];
// Input matrices
printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
scanf("%d", &mat1[i][j]);
}
}
printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
scanf("%d", &mat2[i][j]);
}
}
// Multiply matrices
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
int sum = 0;
for (int k = 0; k < col1; k++) {
sum += mat1[i][k] * mat2[k][j];
}
prod[i][j] = sum;
}
}
// Print product matrix
printf("Product matrix:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
printf("%d ", prod[i][j]);
}
printf("\n");
}
return 0;
}
```
在这个程序中,首先从用户输入中获取两个矩阵的维度,然后检查它们是否可以相乘。如果可以,就分别输入两个矩阵的元素,并使用三重循环计算它们的乘积。最后,输出结果矩阵。
阅读全文
相关推荐















