您好,登錄后才能下訂單哦!
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; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。