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

#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';

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:15
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
07-07 14:30
复旦大学 Java
遇到这种人我也不知道说啥了
无能的丈夫:但我觉得这个hr语气没什么问题啊(没有恶意
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务