输人两个n行 m列的矩阵A和B,输出官们的和A+B,矩阵加法的规则是两个短入中对应位置的值进行加和,具体参照样例。用c++写
时间: 2024-11-20 20:42:25 浏览: 9
在C++中,你可以使用二维数组来表示矩阵,并通过两层循环来实现矩阵的加法操作。以下是一个简单的示例代码:
```cpp
#include <iostream>
using namespace std;
// 定义矩阵类,包含数据成员和尺寸
class Matrix {
private:
int rows;
int cols;
int** data; // 二维整型指针
public:
Matrix(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; ++i)
data[i] = new int[cols];
}
~Matrix() { // 析构函数释放内存
for (int i = 0; i < rows; ++i)
delete[] data[i];
delete[] data;
}
void add(Matrix& other) {
if (rows != other.rows || cols != other.cols) {
cout << "Error: Matrices must have the same dimensions." << endl;
return;
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
data[i][j] += other.data[i][j]; // 对应位置相加
}
}
}
// 其他用于打印矩阵等的方法...
};
int main() {
int n, m;
cout << "Enter number of rows and columns: ";
cin >> n >> m;
Matrix A(n, m);
Matrix B(n, m);
// 输入矩阵A和B的元素
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << "Enter element A(" << i << "," << j << "): ";
cin >> A.data[i][j];
cout << "Enter element B(" << i << "," << j << "): ";
cin >> B.data[i][j];
}
}
// 执行加法
A.add(B);
// 输出结果矩阵A+B
cout << "Matrix A + B:" << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << A.data[i][j] << " ";
}
cout << endl;
}
return 0;
}
阅读全文