1、定义复数
#include <iostream>
using namespace std;
typedef class Complex
{
float realPart;
float imagPart;
public:
Complex() {}
Complex(float real, float imag)
{
realPart = real;
imagPart = imag;
}
float GetRealPart()
{
return realPart;
}
float GetImagPart()
{
return imagPart;
}
void Add(float real, float imag);
void Minus(float real, float imag);
void Multiply(float real, float imag);
void Divide(float real, float imag);
Complex operator + (Complex &c2)
{
Add(c2.GetRealPart(), c2.GetImagPart());
return *this;
}
Complex operator - (Complex &c2)
{
Minus(c2.GetRealPart(), c2.GetImagPart());
return *this;
}
Complex operator * (Complex &c2)
{
Multiply(c2.GetRealPart(), c2.GetImagPart());
return *this;
}
Complex operator / (Complex &c2)
{
Divide(c2.GetRealPart(), c2.GetImagPart());
return *this;
}
}Cplx;
2、类外定义函数
void Complex::Add(float real, float imag)
{
this->realPart += real;
this->imagPart += imag;
}
void Complex::Minus(float real, float imag)
{
this->realPart -= real;
this->imagPart -= imag;
}
void Complex::Multiply(float real, float imag)
{
this->realPart = this->realPart * real - this->imagPart*imag;
this->imagPart = this->imagPart*real+this->realPart*imag;
}
void Complex::Divide(float real, float imag)
{
this->realPart = (this->realPart * real + this->imagPart*imag)/(pow(real,2) + pow(imag,2));
this->imagPart = (this->imagPart*real - this->realPart*imag)/(pow(real, 2) + pow(imag, 2));
}
3、主调函数
int main()
{
Cplx c1 = Cplx(1,2);
Cplx c2 = Cplx(4,5);
Cplx res1 = c1 + c2;
Cplx res2 = c1 - c2;
Cplx res3 = c1 * c2;
Cplx res4 = c1 / c2;
cout << res1.GetRealPart() << " " << res1.GetImagPart() << endl;
cout << res2.GetRealPart() << " " << res2.GetImagPart() << endl;
cout << res3.GetRealPart() << " " << res2.GetImagPart() << endl;
cout << res4.GetRealPart() << " " << res2.GetImagPart() << endl;
return 0;
}
THE END