类的综合运用-complex的实现

实验要求:

定义一个复数类Complex,使得下面的代码能够工作:

Complex c1(3,5);     //用复数3+5i初始化c1;

Compex c2=4.5;      //用实数4.5初始化c2

c1.add(c2);              //将c1与c2相加,结果保存在1中

c1.show();               //将c1输出(这时的结果应该是7.5+5i)

#include<iostream> 
#include <math.h>
using namespace std;
class Complex
{
    public:
        Complex(float r1,float i1); 
        Complex(float r1);
        void add(Complex c);
        double mod();
        void show();
    private:
        float r;
        float i;
};
Complex::Complex(float r1,float i1)
{
    r=r1;
    i=i1;
}
Complex::Complex(float r1)
{
    r=r1;
}
void Complex::add(Complex c)
{
    r+=c.r;
    i+=c.i;
}
double Complex::mod(){
    double m;
    m=sqrt(r*r+i*i);
    return m; 
}

void Complex::show()
{
    cout<<r<<"+"<<i<<"i"<<endl;
}
int main()
{
    Complex c1(3,5);
    Complex c2=4.5;
    c1.add(c2);
    cout<<c1.mod()<<endl;
    c1.show();
}

 

posted @ 2019-03-31 13:28  GeorgeWan  阅读(212)  评论(0编辑  收藏  举报