方法一:使用指针二维数组
#include<iostream>
using namespace std;
int main() {
int m;
int n;
int r;
cout << "运算矩阵A和矩阵B相乘" << endl << endl;
cout << "请输入矩阵A的行数和列数:" << endl << endl;
cout << "矩阵A的行数:";
cin >> m;
cout << "矩阵A的列数:";
cin >> n;
cout << "矩阵B的列数:";
cin >> r;
cout << endl;
//取m的地址赋值给指针x
int *x = &m;
int *y = &n;
int *z = &r;
//把变量m赋值给地址x对应的值,在这里,*x表示在x地址存放的变量值,直接写x表示地址。但在定义的时候不一样,int *x之中,*x就表示的是地址了。
*x = m;
*y = n;
int **a = new int*[*y];
for (int i = 0;i < *x;i++) {
*(a + i) = new int[*x];
}
int **b = new int*[*z];
for (int i = 0;i < *y;i++) {
*(b + i) = new int[*y];
}
int **c = new int*[*z];
for (int i = 0;i < *x;i++) {
*(c + i) = new int[*x];
}
for (int i = 0;i < *x;i++) {
for (int j = 0;j < *z;j++) {
*(*(c + i) + j) = 0;
}
}
cout << "请输入矩阵A:" << endl << endl;
for (int i = 0;i < *x;i++) {
for (int j = 0;j < *y;j++) {
cin >> *(*(a + i) + j);
}
}
cout << endl << "请输入矩阵B:" << endl << endl;
for (int i = 0;i < *y;i++) {
for (int j = 0;j < *z;j++) {
cin >> *(*(b + i) + j);
}
}
//*((a+i)+j) 的意思和 a[i][j]的意思是一样的,只是表示方式不同
for (int i = 0;i < *x;i++) {
for (int j = 0;j < *z;j++) {
for (int k = 0;k < *y;k++) {
*(*(c + i) + j) = *(*(c + i) + j) + (*(*(a + i) + k)**(*(b + k) + j));
}
}
}
cout << endl << endl << "矩阵A乘以矩阵B的结果:" << endl << endl;
for (int i = 0;i < *x;i++) {
for (int j = 0;j < *z;j++) {
cout << *(*(c + i) + j) << "\t";
}
cout << endl << endl;
}
return 0;
}
方法二:直接声明固定大小的二维数组
#include<iostream>
using namespace std;
int main() {
int m;
int n;
int r;
cout << "运算矩阵A和矩阵B相乘" << endl << endl;
cout << "请输入矩阵A的行数和列数:" << endl << endl;
cout << "矩阵A的行数:";
cin >> m;
cout << "矩阵A的列数:";
cin >> n;
cout << "矩阵B的列数:";
cin >> r;
cout << endl;
int a[m][n];
int b[n][r];
int c[m][r];
for (int i = 0;i < m;i++) {
for (int j = 0;j < r;j++) {
c[i][j] = 0;
}
}
cout << "请输入矩阵A:" << endl << endl;
for (int i = 0;i < m;i++) {
for (int j = 0;j < n;j++) {
cin >> a[i][j];
}
}
cout << endl << "请输入矩阵B:" << endl << endl;
for (int i = 0;i < n;i++) {
for (int j = 0;j < r;j++) {
cin >> b[i][j];
}
}
for (int i = 0;i < m;i++) {
for (int j = 0;j < r;j++) {
for (int k = 0;k < n;k++) {
c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
}
}
}
cout << endl << endl << "矩阵A乘以矩阵B的结果:" << endl << endl;
for (int i = 0;i < m;i++) {
for (int j = 0;j < r;j++) {
cout << c[i][j] << "\t";
}
cout << endl << endl;
}
return 0;
}
其中方法一有个比较大的缺点,就是当输入一个比大的矩阵的时候,会产生野指针,或者提前结束程序。
方法二问题不大
方法一运行效果:
如果输入较大的数字,比如行列数大于等于7就会出问题了
方法二运行结果: