今天我们用C++来实现一下复数的加减运算及比较大小
先来大概说明一下复数的运算。
1.加法运算:(a+bi)+(c+di)=(a+c)+(b+d)i
2.减法运算:(a+bi)-(c+di)=(a-c)+(b-d)i
3.乘法运算:(a+bi)*(c+di)=(ac-bd)*(ad+bc)i
4.除法运算:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2)+(bc-ad)i/(c^2+d^2)
直接上代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdlib.h>
using namespace std;
class Complex
{
public:
Complex(double real, double image)
: _real(real)
, _image(image)
{}
~Complex()
{}
Complex operator+(const Complex& c)
{
Complex ret(_real + c._real, _image + c._image);
return ret;
}
Complex operator-(const Complex& c)
{
return Complex(_real - c._real, _image - c._image);
}
//两复数相乘:(a+bi)*(c+di)=(ac-bd)*(ad+bc)i
Complex operator*(const Complex& c)
{
return Complex(_real*c._real - _image*c._image, _real*c._image + _image*c._real);
}
//两复数相除:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2)+(bc-ad)i/(c^2+d^2)
Complex operator/(const Complex& c)
{
return Complex((_real*c._real + _image*c._image)\
/ (c._real*c._real + c._image*c._image)\
,(_image*c._real - _real*c._image)\
/ (c._real*c._real + c._image*c._image));
}
Complex& operator+=(const Complex&c)
{
_real = this->_real + c._real;
_image = this->_image + c._image;
return *this;
}
Complex& operator-=(const Complex&c)
{
_real = this->_real - c._real;
_image = this->_image - c._image;
return *this;
}
Complex& operator*=(const Complex&c)
{
double real0 = _real;
_real = real0 * c._real - _image * c._image;
_image = real0 * c._image + _image * c._real;
return *this;
}
Complex& operator/=(const Complex&c)
{
double real0 = _real;
_real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
_image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return *this;
}
Complex& operator=(const Complex&c)
{
cout << this << "=" << &c << endl;
if (this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
bool operator>(const Complex& c)
{
if(this->_image != 0 || c._image != 0)
{
cout << "虚数不能比较大小" << endl;
return false;
}
else
{
if(_real > c._real)
{
return true;
}
else
return false;
}
}
bool operator<(const Complex& c)
{
if(this->_image != 0 || c._image != 0)
{
cout << "虚数不能比较大小" << endl;
return false;
}
return !(*this > c);
}
bool operator==(const Complex& c)
{
if ((this->_real == c._real) && (this->_image == c._image))
return true;
return false;
}
bool operator!=(const Complex& c)
{
if ((this->_real != c._real) || (this->_image != c._image))
return true;
return false;
}
friend ostream& operator<<(ostream& out, const Complex& c)
{
out << "real=" << c._real << endl;
out << "image=" << c._image << endl;
return out;
}
private:
double _real;
double _image;
};
来测试一下:
int main()
{
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1*c2;
Complex c6 = c1 / c2;
cout << c3 << endl;
cout << c4 << endl;
cout << c5 << endl;
cout << c6 << endl;
c1 = c2 = c3;
c1 = c2.operator=(c3);
system("pause\n");
return 0;
}
看一下输出结果吧!