两个指针矩阵相乘输出结果c++
时间: 2023-11-24 16:51:48 浏览: 95
学习二维动态数组指针做矩阵运算的方法
根据提供的引用内容,没有直接给出两个指针矩阵相乘的代码。但是可以根据引用中的矩阵读入函数和以下代码,实现两个指针矩阵相乘并输出结果:
```c++
#include <iostream>
using namespace std;
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;
}
void printMatrix(double** matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%lf ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int rows1, cols1, rows2, cols2;
double** matrix1 = readMatrix(&rows1, &cols1);
double** matrix2 = readMatrix(&rows2, &cols2);
if (cols1 != rows2) {
printf("Error: The number of columns in the first matrix must be equal to the number of rows in the second matrix.\n");
return 0;
}
double** result = (double**)malloc(rows1 * sizeof(double*));
for (int i = 0; i < rows1; i++) {
result[i] = (double*)malloc(cols2 * sizeof(double));
}
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
printMatrix(result, rows1, cols2);
return 0;
}
```
阅读全文