C++实现求复数的模长

实现原理:先定义一个复数类含有实部、虚部和模长,然后再定义一个求模长的函数。

//C++ 实现求复数的模
#include <cmath>//sqrt()函数的头文件
#include <iostream>
using namespace std;

class Complex//定义复数的类
{

public:
	Complex();//构造函数初始化变量
	Complex(float _x, float _y);
	float get_x();
	float get_y();
	float get_m();
	void set_x(float _x);
	void set_y(float _y);
	void set_m(float m);
	void display();//打印结果
	
private:
	float x;//定义实部
	float y;//定义虚部
	float modul;//定义模长

};

Complex add(Complex &p1, Complex &p2);//求模长函数
int main()
{
	Complex d1(2.1, 3.4), d2(6.1, 3.1), d3;
	d3 = add(d1, d2);
	d3.display();
	return 0;
}
Complex::Complex()
{
	x = 0;
	y = 0;
	modul = 0;
}
Complex::Complex(float _x, float _y)
{
	x = _x;
	y = _y;
	
}
float Complex::get_x()
{
	return x;
}
float Complex::get_y()
{
	return y;
}
float Complex::get_m()
{
	return modul;
}
void Complex::set_m(float m)
{
	modul = m;
}
void Complex::set_x(float _x)
{
	x = _x;
}
void Complex::set_y(float _y)
{
	y = _y;
}
Complex add(Complex &p1, Complex &p2)
{
	Complex p3;
	p3.set_x(p1.get_x() + p2.get_x());
	p3.set_y(p1.get_y() + p2.get_y());
	p3.set_m(sqrt(p1.get_x() * p2.get_x() + p1.get_y() * p2.get_y()));//求模长
	return p3;
}
void Complex::display()
{
	cout << "模长为:" << get_m() << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值