用C++实现这样一个程序:输入任意大小的两个矩阵。计算两个矩阵的乘积并输出在终端
时间: 2023-02-05 11:01:50 浏览: 120
好的,下面是用 C 语言实现的程序,它可以输入两个任意大小的矩阵,并计算它们的乘积并在终端输出。
首先,需要包含 stdio.h 和 stdlib.h 头文件。
然后,定义一个函数用于读入矩阵的大小和元素,并返回一个指向矩阵的指针。
```
double** readMatrix(int* rows, int* cols) {
// 读入矩阵的行数和列数
scanf("%d %d", rows, cols);
// 分配内存空间存储矩阵
double** matrix = (double**)malloc(*rows * sizeof(double*));
for (int i = 0; i < *rows; i++) {
matrix[i] = (double*)malloc(*cols * sizeof(double));
}
// 读入矩阵的元素
for (int i = 0; i < *rows; i++) {
for (int j = 0; j < *cols; j++) {
scanf("%lf", &matrix[i][j]);
}
}
return matrix;
}
```
然后,定义一个函数用于计算两个矩阵的乘积并返回结果矩阵。
```
double** matrixMultiply(double** A, int A_rows, int A_cols, double** B, int B_rows, int B_cols) {
// 分配内存空间存储结果矩阵
double** C = (double**)malloc(A_rows * sizeof(double*));
for (int i = 0; i < A_rows; i++) {
C[i] = (double*)malloc(B_cols * sizeof(double));
}
// 计算矩阵乘积
for (int i = 0; i < A_rows; i++) {
for (int j = 0; j < B_cols; j++) {
C[i][j] = 0;
for (int k = 0; k < A_cols; k++) {
C[i][j] += A[i][k] * B[k][j];