自己定义一个复数类型,可以进行复数的基本运算

#include<iostream>

using namespace std;

struct complex

{

double real,imag;

complex(double r=0.0,double i=0.0):real(r),imag(i){};

complex operator+ (const complex & other)const

{

return complex(real+other.real,imag+other.imag);

}

complex operator- (const complex &other)const

{

return complex(real-other.real,imag-other.imag);

}

complex operator* (const complex &other)const

{

return complex(real*other.real-imag*other.imag,real*other.imag+other.real*imag);

}

};

ostream& operator<<(ostream& os,const complex&c){if(c.imag>=0){os<<c.real<<"+"<<c.imag<<"i";}

else{os<<c.real<<c.imag<<"i";}return os;}

istream& operator >>(istream& is, complex &c){is>>c.real>>c.imag;return is;}

int main()

{

complex a,b;

cin>>a>>b;

cout<<a+b<<'\n';

cout<<a-b<<'\n';

cout<<a*b<<'\n';

}

全部评论

相关推荐

评论
1
收藏
分享
牛客网
牛客企业服务