定义一个复数类complex,用运算符重载的方法实现复数的加减乘除运算.要求分别实现 20

 我来答
笃侠6A
2012-06-28 · TA获得超过3734个赞
知道大有可为答主
回答量:3205
采纳率:75%
帮助的人:3224万
展开全部
#include <iostream>using namespace std;
class Complex{ double real; double imag;public: Complex() //默认构造函数 { real=0; imag=0; } Complex(double r,double i) //实现初始化的构造函数 { real=r; imag=i; } Complex operator+(Complex& c2); Complex operator-(Complex& c2); Complex operator*(Complex& c2); Complex operator/(Complex& c2); void display();}; Complex Complex::operator+(Complex& c2){ return Complex(real+c2.real, imag+c2.imag);} Complex Complex::operator-(Complex& c2){ return Complex(real-c2.real, imag-c2.imag);}// (a+bi)*(c+di)=(ac-bd)+(bc+ad)iComplex Complex::operator*(Complex& c2){ Complex c; c.real=real*c2.real-imag*c2.imag; c.imag=imag*c2.real+real*c2.imag; return c;}
//(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c^2+d^2))iComplex Complex::operator/(Complex& c2){ Complex c; double d=imag*imag+c2.imag*c2.imag; c.real=(real*c2.real+imag*c2.imag)/d; c.imag=(imag*c2.real-real*c2.imag)/d; return c;}
void Complex::display(){ cout<<"("<<real<<(imag>=0 ? '+' : ' ')<<imag<<"i)"<<endl;}
int main(){ Complex c1(3,4),c2(5,-10),c3,c4,c5,c6; c3=c1+c2; c4=c1-c2; c5=c1*c2; c6=c1/c2; c3.display(); c4.display(); c5.display(); c6.display();
return 0;}
Annneie
2012-06-28
知道答主
回答量:31
采纳率:0%
帮助的人:13.6万
展开全部
#include <iostream>
using namespace std;
class Complex{
public:
Complex(double r=0.0,double i=0.0): real(r), imag(i){}
Complex operator+(const Complex &c2) const;
Complex operator-(const Complex &c2) const;
Complex operator*(const Complex &c2) const;
Complex operator/(const Complex &c2) const;
void display() const;
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex &c2) const{
return Complex(real+c2.real, imag+c2.imag);
}
Complex Complex::operator-(const Complex &c2) const{
return Complex(real-c2.real, imag-c2.imag);
}
Complex Complex::operator*(const Complex &c2) const{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
Complex Complex::operator/(const Complex &c2) const{
Complex c;
double d=imag*imag+c2.imag*c2.imag;
c.real=(real*c2.real+imag*c2.imag)/d;
c.imag=(imag*c2.real-real*c2.imag)/d;
return c;
}
void Complex::display() const{
cout<<"("<<real<<","<<imag<<")"<<endl;
}
int main(){
Complex c1(5,4),c2(2,10),c3;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
c3=c1+c2;
cout<<" c3=c1+c2=";c3.display();
c3=c1-c2;
cout<<" c3=c1-c2=";c3.display();
c3=c1*c2;
cout<<" c3=c1*c2=";c3.display();
c3=c1/c2;
cout<<" c3=c1/c2=";c3.display();
return 0;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式