二、用C++实现复数结构

本文档实现了一个复数类,包括实部和虚部,提供了构造函数、获取实部和虚部的方法,以及复数的加、减、乘、除运算。类外定义了相关操作函数,并在主函数中展示了类的使用,通过实例计算了复数的四则运算结果。

1、定义复数

#include <iostream>

using namespace std;

typedef class Complex
{
	float realPart;
	float imagPart;
public:
	Complex() {}
	Complex(float real, float imag)
	{
		realPart = real;
		imagPart = imag;
	}
	float GetRealPart()
	{//获得实数部分
		return realPart;
	}
	float GetImagPart()
	{//获得虚数部分
		return imagPart;
	}
	void Add(float real, float imag);			//复数相加
	void Minus(float real, float imag);			//复数相减
	void Multiply(float real, float imag);		//复数相乘
	void Divide(float real, float imag);		//复数相除

	//运算符重载
	Complex operator + (Complex &c2)
	{
		Add(c2.GetRealPart(), c2.GetImagPart());
		return *this;
	}

	Complex operator - (Complex &c2)
	{
		Minus(c2.GetRealPart(), c2.GetImagPart());
		return *this;
	}

	Complex operator * (Complex &c2)
	{
		Multiply(c2.GetRealPart(), c2.GetImagPart());
		return *this;
	}

	Complex operator / (Complex &c2)
	{
		Divide(c2.GetRealPart(), c2.GetImagPart());
		return *this;
	}

}Cplx;//类重命名

2、类外定义函数

//类内声明,类外定义
void Complex::Add(float real, float imag)
{
	this->realPart += real;
	this->imagPart += imag;
}

void Complex::Minus(float real, float imag)
{
	this->realPart -= real;
	this->imagPart -= imag;
}

void Complex::Multiply(float real, float imag)
{
	this->realPart = this->realPart * real - this->imagPart*imag;//(ac-bd)
	this->imagPart = this->imagPart*real+this->realPart*imag;//(bc+ad)
}

void Complex::Divide(float real, float imag)
{
	this->realPart = (this->realPart * real + this->imagPart*imag)/(pow(real,2) + pow(imag,2));//(ac+bd)/(c^2+d^2)
	this->imagPart = (this->imagPart*real - this->realPart*imag)/(pow(real, 2) + pow(imag, 2));//(bc-ad)/(c^2+d^2)
}

3、主调函数

int main()
{
	Cplx c1 = Cplx(1,2);
	Cplx c2 = Cplx(4,5);

	Cplx res1 = c1 + c2;
	Cplx res2 = c1 - c2;
	Cplx res3 = c1 * c2;
	Cplx res4 = c1 / c2;

	cout << res1.GetRealPart() << "	" << res1.GetImagPart() << endl;
	cout << res2.GetRealPart() << "	" << res2.GetImagPart() << endl;
	cout << res3.GetRealPart() << "	" << res2.GetImagPart() << endl;
	cout << res4.GetRealPart() << "	" << res2.GetImagPart() << endl;


	return 0;
}

THE END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dragon Fly

多谢老板赏钱[抱拳抱拳抱拳]

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

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

打赏作者

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

抵扣说明:

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

余额充值