- 矩阵乘法(C++一维数组实现)
#include<iostream>
using namespace std;
class matirx {
private:
int rows;
int cols;
int* mValue;
public:
matirx() {}
void initMatirx() {
cout << "请输入行数:";
cin >> this->rows;
cout << endl;
cout << "请输入列数:";
cin >> this->cols;
cout << endl;
this->mValue = new int[rows * cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
cout << "请输入m[" << i + 1 << "][" << j + 1 << "]:";
cin >> mValue[i * cols + j];
cout << endl;
}
}
void deleteMatirx() {
delete[] this->mValue;
}
void printMatirx() {
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++) {
cout << mValue[i * cols+ j]<<"\t";
}
cout << endl;
}
}
matirx operator+(const matirx &m2) {
if (this->cols != m2.rows) {
cout << "input error!!!";
return matirx();
}
matirx m3;
m3.mValue = new int[rows * m2.cols];
m3.rows = rows;
m3.cols = m2.cols;
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < m2.cols; j++) {
for (int k = 0; k < cols; k++) {
sum += mValue[i * cols + k] * m2.mValue[j + k * m2.cols];
}
m3.mValue[i*m2.cols + j ] = sum;
sum = 0;
}
}
return m3;
}
int getRows() {
return this->rows;
}
int getCols() {
return this->cols;
}
};
int main()
{
matirx m1,m2,m3;
m1.initMatirx();
m2.initMatirx();
cout << "m1:" << endl;
m1.printMatirx();
cout << "m2:" << endl;
m2.printMatirx();
m3 = m1 + m2;
m3.printMatirx();
}