您好,登錄后才能下訂單哦!
C++中實(shí)現(xiàn)矩陣的加法和乘法實(shí)例
實(shí)現(xiàn)效果圖:
實(shí)例代碼:
#include<iostream> using namespace std; class Matrix { int row;//矩陣的行 int col;//矩陣的列 int **a;//保存二維數(shù)組的元素 public: Matrix();//默認(rèn)構(gòu)造函數(shù) Matrix(int r, int c); Matrix(const Matrix &is);//拷貝構(gòu)造函數(shù) 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("請輸入數(shù):\n"); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) cin >> a[i][j]; } Matrix::Matrix(const Matrix & is) {//拷貝構(gòu)造函數(shù) 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; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。