定义一个Matrix类,实现矩阵的加法和乘法
#include<iostream> using namespace std; class Matrix { int row;//矩阵的行 int col;//矩阵的列 int **a;//保存二维数组的元素 public: Matrix();//默认构造函数 Matrix(int r, int c); Matrix(const Matrix &is);//拷贝构造函数 void Madd(const Matrix &is);//矩阵加 Matrix Mmul(const Matrix &is);//矩阵乘 void display();//显示矩阵元素 }; Matrix::Matrix(int r, int c) { row = r; col = c; a = (int **)malloc(sizeof(int*)*row); for (int r = 0; r < row; r++) { *(a + r) = (int*)malloc(sizeof(int)*col); } printf("请输入数:\n"); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) cin >> a[i][j]; } Matrix::Matrix(const Matrix & is) {//拷贝构造函数 row = is.row; col = is.col; a = new int*[row]; for (int i = 0; i < row; i++) { a[i] = new int[col]; } a = is.a; } void Matrix::Madd(const Matrix & is) { if (row != is.row || col != is.col)//判断两矩阵是否符合相加条件 { cout << "相加的矩阵必须行和列一致"; } else { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] += is.a[i][j]; } } } } Matrix Matrix::Mmul(const Matrix & is) { Matrix M3(this->row, is.col); if (this->col != is.row)//判断是否符合相乘条件 { cout << "不符合两矩阵相乘的条件"; } else { for (int i = 0; i < M3.row; i++) { for (int j = 0; j < M3.col; j++) { M3.a[i][j] = 0; for (int n = 0; n < is.row; n++) { M3.a[i][j] += this->a[i][n] * is.a[n][j]; } } } } return M3; } void Matrix::display() {//输出矩阵 for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << a[i][j] << " "; } cout << endl; } cout << endl; } int main() { Matrix m1(3, 3); m1.display(); Matrix m2(3, 3); m2.display(); Matrix m3(3, 2); m3.display(); cout << "m1+m2=" << endl; m1.Madd(m2); m1.display(); Matrix m4(m1.Mmul(m3)); cout << "m1*m3=" << endl; m4.display(); system("pause"); return 0; }
运行结果:
相关推荐
zhoujiyu 2020-06-28
xiaoxue 2020-05-02
seasongirl 2020-02-02
jling 2020-01-29
wklken的笔记 2020-01-11
kuoying 2019-12-20
坚持是一种品质 2019-11-08
wanff0 2019-10-29
liusarazhang 2019-10-21
youmianzhou 2019-05-24
Datawhale 2019-05-18
mieleizhi0 2019-03-26
algorithmlixuan 2014-07-22
pengkunstone 2019-06-30
amazingbo 2019-06-28
Ryuchong 2019-06-27
郭岚 2019-06-27
HappinessSourceL 2019-06-25
perseverancep 2011-11-28