复数四则运算 编程
发布网友
发布时间:2022-06-01 19:01
我来回答
共1个回答
热心网友
时间:2023-10-12 15:26
#include <iostream.h>
class Complex{
private:
float _real;
float _image;
public:
Complex(float real=0,float image=0);
Complex operator +(const Complex &rhs);
Complex operator -(const Complex &rhs);
Complex operator *(const Complex &rhs);
float GetReal()const;
float GetImage()const;
};
Complex::Complex(float real,float image)
{
_real=real;
_image=image;
}
Complex Complex::operator +(const Complex &rhs)
{
_real+=rhs.GetReal();
_image+=rhs.GetImage();
return *this;
}
Complex Complex::operator -(const Complex &rhs)
{
_real-=rhs.GetReal();
_image-=rhs.GetImage();
return *this;
}
Complex Complex::operator *(const Complex &rhs)
{
_real=_real*rhs.GetReal()-_image*rhs.GetImage();
_image=_real*rhs.GetImage()+_image*rhs.GetReal();
return *this;
}
float Complex::GetReal()const
{
return _real;
}
float Complex::GetImage()const
{
return _image;
}
void main()
{
cout<<"依次输入两个复数的实部和虚部"<<endl;
float realA,imageA,realB,imageB;
cin>>realA>>imageA>>realB>>imageB;
Complex A(realA,imageA);
Complex B(realB,imageB);
Complex temp;
//减法和乘法类似
temp=A+B;
cout<<"两者之和为:"<<temp.GetReal()<<"+"<<temp.GetImage()<<"i"<<endl;
cout<<"其实部为"<<temp.GetReal()<<"虚部为"<<temp.GetImage()<<endl;
}