C++中實現矩陣的加法和乘法實例。本站提示廣大學習愛好者:(C++中實現矩陣的加法和乘法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++中實現矩陣的加法和乘法實例正文
C++中實現矩陣的加法和乘法實例
實現效果圖:
實例代碼:
#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; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!