栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 1、定义复数
  • 2、类外定义函数
  • 3、主调函数
  • THE END

1、定义复数
#include 

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429573.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号