4、编写函数,给定两个矩阵A和B,计算它们的乘积矩阵AB。其中矩阵的值从主函数中输入和输出。 注意:只有规模匹配的矩阵才可以相乘。即若A有Ra行、Ca列,B有Rb行、Cb列, 则只有Ca=Rb时,A和B才能相乘。用C语言编写
时间: 2025-06-14 13:16:23 浏览: 16
在C语言中,我们可以使用嵌套循环来计算两个矩阵的乘积。假设我们有两个二维数组`A`和`B`,它们的尺寸分别为`(row_a, col_a)`和`(row_b, col_b)`,那么只有当`col_a == row_b`时,这两个矩阵才允许相乘。以下是计算矩阵乘积的函数示例:
```c
#include <stdio.h>
#define MAX_ROWS 100
#define MAX_COLS 100
// 定义矩阵结构体
typedef struct {
int data[MAX_COLS][MAX_COLS];
int rows, cols;
} Matrix;
// 初始化矩阵
Matrix create_matrix(int row, int col, const int values[]) {
Matrix m;
m.rows = row;
m.cols = col;
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
m.data[i][j] = values[i * col + j];
return m;
}
// 计算矩阵乘积
void matrix_multiply(Matrix A, Matrix B, Matrix result) {
if (A.cols != B.rows) {
printf("矩阵无法相乘,列数不匹配!\n");
return;
}
for (int i = 0; i < A.rows; ++i) {
for (int j = 0; j < B.cols; ++j) {
int sum = 0;
for (int k = 0; k < A.cols; ++k) {
sum += A.data[i][k] * B.data[k][j];
}
result.data[i][j] = sum;
}
}
}
// 输出矩阵
void print_matrix(const Matrix& m) {
for (int i = 0; i < m.rows; ++i) {
for (int j = 0; j < m.cols; ++j) {
printf("%d ", m.data[i][j]);
}
printf("\n");
}
}
int main() {
int row_a, col_a, row_b, col_b;
printf("Enter the dimensions of matrix A (rows and columns): ");
scanf("%d %d", &row_a, &col_a);
printf("Enter the dimensions of matrix B (rows and columns): ");
scanf("%d %d", &row_b, &col_b);
if (col_a != row_b) {
printf("矩阵无法相乘,列数不匹配!\n");
return 1;
}
int values_A[row_a * col_a], values_B[row_b * col_b];
printf("Enter the elements of matrix A:\n");
for (int i = 0; i < row_a * col_a; ++i) {
scanf("%d", &values_A[i]);
}
printf("Enter the elements of matrix B:\n");
for (int i = 0; i < row_b * col_b; ++i) {
scanf("%d", &values_B[i]);
}
Matrix A = create_matrix(row_a, col_a, values_A);
Matrix B = create_matrix(row_b, col_b, values_B);
Matrix C;
matrix_multiply(A, B, C);
printf("Matrix product AB is:\n");
print_matrix(C);
return 0;
}
阅读全文
相关推荐


















