利用c++语言分别实现矩阵相乘相加相减
时间: 2024-09-06 09:06:04 浏览: 53
在C++中,我们可以使用二维数组或者矩阵类来实现矩阵的相乘、相加和相减。这里我会给出基本的函数实现示例:
```cpp
#include <iostream>
using namespace std;
// 定义矩阵类,包含行数和列数
class Matrix {
private:
int m, n;
double arr[100][100]; // 假设矩阵大小不超过100x100
public:
Matrix(int r, int c) : m(r), n(c) {}
// 矩阵赋值
void assignMatrix(int r, int c, double (*matrix)[c]) {
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
arr[i][j] = matrix[i][j];
}
// 矩阵相加
Matrix operator+(const Matrix& other) const {
if (m != other.m || n != other.n)
throw "Matrices are not of the same size for addition!";
Matrix result(m, n);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
result.arr[i][j] = arr[i][j] + other.arr[i][j];
return result;
}
// 矩阵相减
Matrix operator-(const Matrix& other) const {
if (m != other.m || n != other.n)
throw "Matrices are not of the same size for subtraction!";
Matrix result(m, n);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
result.arr[i][j] = arr[i][j] - other.arr[i][j];
return result;
}
};
// 主函数展示例子
int main() {
Matrix A(3, 3), B(3, 3), C(3, 3);
// 初始化A和B的矩阵数据...
// 相加
C = A + B;
cout << "Matrix addition:\n";
C.assignMatrix(A.m, A.n, &C.arr); // 打印结果
// 相减
C = A - B;
cout << "\nMatrix subtraction:\n";
C.assignMatrix(A.m, A.n, &C.arr); // 打印结果
return 0;
}
```
在这个示例中,我们首先创建了一个矩阵类`Matrix`,包含了矩阵的尺寸和元素数组。然后定义了`operator+`和`operator-`运算符重载,用于实现矩阵的相加和相减。在`main()`函数里,我们实例化两个矩阵并进行了操作。
阅读全文