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

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

}

全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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