用c加加编写程序,求nXm 和mXk矩阵之积
时间: 2025-01-18 11:03:57 浏览: 40
在C++中,为了计算两个矩阵的乘积,你需要理解矩阵乘法的基本规则,并使用嵌套循环来实现。这里是一个简单的示例,展示如何用C++编写一个函数来计算两个给定维度的矩阵相乘:
```cpp
#include <iostream>
using namespace std;
// 定义矩阵类,包含行数、列数和元素数组
class Matrix {
private:
int rows, cols;
double data[100][100]; // 假设每个矩阵最大有100x100
public:
// 构造函数,初始化矩阵大小
Matrix(int r, int c) : rows(r), cols(c) {}
// 显示矩阵内容
void display() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j)
cout << data[i][j] << " ";
cout << endl;
}
}
// 矩阵乘法,检查是否可以相乘(列数等于另一个矩阵的行数)
friend Matrix operator*(Matrix& m1, Matrix& m2);
};
// 实现矩阵乘法运算符重载
Matrix Matrix::operator*(Matrix& m2) {
if (cols != m2.rows) {
throw invalid_argument("Invalid matrix multiplication: columns of first matrix don't match rows of second matrix.");
}
Matrix result(rows, m2.cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < m2.cols; ++j) {
double sum = 0;
for (int k = 0; k < cols; ++k) {
sum += data[i][k] * m2.data[k][j];
}
result.data[i][j] = sum;
}
}
return result;
}
int main() {
int n, m, k;
cout << "Enter the dimensions of the two matrices (n and m): ";
cin >> n >> m;
cout << "Enter the dimensions of the third matrix (m and k): ";
cin >> m >> k;
// 创建并填充矩阵
Matrix A(n, m), B(m, k), C(n, k);
cout << "Enter elements of matrix A:\n";
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
cin >> A.data[i][j];
cout << "Enter elements of matrix B:\n";
for (int i = 0; i < m; ++i)
for (int j = 0; j < k; ++j)
cin >> B.data[i][j];
try {
Matrix product = A * B;
cout << "\nProduct of matrices AB is:\n";
product.display();
} catch (invalid_argument& e) {
cerr << e.what() << endl;
}
return 0;
}
```
在这个例子中,用户输入两个矩阵A和B的维度,然后输入它们的元素。`operator*`函数实现了矩阵乘法,如果矩阵A的列数和矩阵B的行数不匹配,会抛出异常。最后,我们得到矩阵AB的结果。
阅读全文
相关推荐


















