复数加减乘除实现(C++)

源码

(因为是昨晚写的,分析过程忘了,大家就直接看源码好了,反正还蛮简单的hhh)
#include <iostream>
using namespace std;
class complex
{
public:
	complex(int i = 0, int j = 0) :a(i), b(j) {}
	~complex() {};
	complex operator+(complex y)
	{
		complex temp;
		temp.a = a + y.a;
		temp.b = b + y.b;
		return temp;
	}
	complex operator-(complex y)
	{
		complex temp;
		temp.a = a - y.a;
		temp.b = b - y.b;
		return temp;
	}
	complex operator*(complex y)
	{
		complex temp;
		temp.a = a * y.a - b * y.b;
		temp.b = a * y.b + b * y.a;
		return temp;
	}
	complex operator/(complex y)
	{
		complex temp;
		temp.a = (a * y.a + b * y.b) / (y.a * y.a + y.b * y.b);
		temp.b = (b * y.a + a * y.b) / (y.a * y.a + y.b * y.b);
		return temp;
	}
	void getcomplex(float& aa, float& bb)
	{
		aa = a;
		bb = b;
	}

private:
	float a, b;
};
ostream& operator<<(ostream& os, complex& s)
{
	float a, b;
	s.getcomplex(a, b);
	os << a << "+" << b << "i";
	return os;
}
int main()
{
	complex x(1,1),y(1,1),z;
	z = x + y;
	cout << z << endl;
	z = x - y;
	cout << z << endl;
	z = x * y;
	cout << z << endl;
	z = x / y;
	cout << z << endl;
	return 0;
}

复数加减乘除可以通过运算符重载来实现,下面是一个简单的复数类及其运算符重载实现: ```c++ #include <iostream> class Complex { public: Complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) {} Complex operator+(const Complex& other) const { return Complex(m_real + other.m_real, m_imag + other.m_imag); } Complex operator-(const Complex& other) const { return Complex(m_real - other.m_real, m_imag - other.m_imag); } Complex operator*(const Complex& other) const { double real = m_real * other.m_real - m_imag * other.m_imag; double imag = m_real * other.m_imag + m_imag * other.m_real; return Complex(real, imag); } Complex operator/(const Complex& other) const { double denominator = other.m_real * other.m_real + other.m_imag * other.m_imag; double real = (m_real * other.m_real + m_imag * other.m_imag) / denominator; double imag = (m_imag * other.m_real - m_real * other.m_imag) / denominator; return Complex(real, imag); } friend std::ostream& operator<<(std::ostream& out, const Complex& c) { out << c.m_real << " + " << c.m_imag << "i"; return out; } private: double m_real; double m_imag; }; int main() { Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; Complex c4 = c1 - c2; Complex c5 = c1 * c2; Complex c6 = c1 / c2; std::cout << c3 << std::endl; std::cout << c4 << std::endl; std::cout << c5 << std::endl; std::cout << c6 << std::endl; return 0; } ``` 运行结果: ``` 4 + 6i -2 - 2i -5 + 10i 0.44 - 0.08i ``` 注意,这里实现的是复数的基本运算,可能还需要根据具体需求扩展其他功能。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

chaoql

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

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

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

打赏作者

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

抵扣说明:

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

余额充值