C++实现求复数的模长

2019-04-13 14:39发布

实现原理:先定义一个复数类含有实部、虚部和模长,然后再定义一个求模长的函数。
//C++ 实现求复数的模
#include //sqrt()函数的头文件
#include
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;
}