C++实现复数矩阵乘法运算

#include <iostream>
#include <vector>

// 复数类
class Complex {
public:
	double real, imag;

	Complex():real(0.0),imag(0.0){}
	Complex(double r, double i) : real(r), imag(i) {}

	Complex operator+(const Complex &c) const {
		return Complex(real + c.real, imag + c.imag);
	}

	Complex operator-(const Complex &c) const {
		return Complex(real - c.real, imag - c.imag);
	}

	Complex operator*(const Complex &c) const {
		return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
	}
};

// 矩阵类
class Matrix {
public:
	int rows, cols;
	std::vector<std::vector<Complex>> data;

	Matrix(int r, int c) : rows(r), cols(c), data(r, std::vector<Complex>(c)) {}

	// 复数矩阵相乘
	Matrix mul(const Matrix &m) const {
		Matrix result(rows, m.cols);
		for (int i = 0; i < rows; ++i) {
			for (int j = 0; j < m.cols; ++j) {
				for (int k = 0; k < cols; ++k) {
					result.data[i][j] = result.data[i][j] + data[i][k] * m.data[k][j];
				}
			}
		}
		return result;
	}
};

int main() {
	// 示例:创建两个2x2的复数矩阵并计算乘积
	Matrix A(2, 2);
	Matrix B(2, 2);
	A.data = { { Complex(1.0, 2.0), Complex(3.0, 4.0) },{ Complex(5.0, 6.0), Complex(7.0, 8.0) } };
	B.data = { { Complex(9.0, 10.0), Complex(11.0, 12.0) },{ Complex(13.0, 14.0), Complex(15.0, 16.0) } };

	Matrix C = A.mul(B);

	// 输出结果
	for (int i = 0; i < C.rows; ++i) {
		for (int j = 0; j < C.cols; ++j) {
			std::cout << C.data[i][j].real << " + " << C.data[i][j].imag << "i" << " ";
		}
		std::cout << std::endl;
	}
	system("pause");
	return 0;
}

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI1.0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值