使用模板类实现复数的四则运算

时间:2022-10-25 20:40:31

复数:是指能写成如下形式的数a+bi,这里a和b是实数,i是虚数单位, i*i = -1

在复数 a+bi a为复式的实部 , b为复数的虚部


复数的四则运算:

(a+bi)+ (c+di)= (a+c)+ (b+d)i; 

(a+bi)- (c+di) = (a-c) + (b-d)i;

(a+bi)* (c+di) = (ac-bd)+ (ad+bc)i;

(a+bi)/ (c+di)= ((ac+bd)+(bc-ad)i) / (c*c+d*d);


程序代码:

#include <iostream>

using namespace std;

template<class T>//类声明前加模板的声明

class Complex
{
public:
Complex( )
{
real=0;
imag=0;
}

Complex(T r,T i)
{
real=r;
imag=i;
}

Complex complex_add(Complex &c2);//复数的加法
Complex complex_minus(Complex &c2);//复数的减法
Complex complex_multiply(Complex &c2);//复数的乘法
Complex complex_divide(Complex &c2);//复数的除法
void display( );//显示复数

private:
T real;//复数的实部
T imag;//复数的虚部
};

template<class T>
Complex<T> Complex<T>::complex_add(Complex &c2)//复数的加法
{
Complex c3;

c3.real = real + c2.real;
c3.imag = imag + c2.imag;

return c3;
}

template<class T>
Complex<T> Complex<T>::complex_minus(Complex &c2)//复数的减法
{
Complex c3;

c3.real = real - c2.real;
c3.imag = imag - c2.imag;

return c3;
}

template<class T>
Complex<T> Complex<T>::complex_multiply(Complex &c2)//复数的乘法
{
Complex c3;

c3.real = real*c2.real - imag * c2.imag;
c3.imag = real*c2.imag + imag * c2.real;

return c3;
}

template<class T>
Complex<T> Complex<T>::complex_divide(Complex &c2)//复数的除法
{
Complex c3;

c3.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);

c3.imag = (imag * c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);

return c3;
}

template<class T>
void Complex<T>::display( )//显示复数
{

if(imag > 0)//当虚部大于0时
{
cout<<real<<'+'<<imag<<'i';
}
else if(0 == imag)//当虚部等于0时
{
cout<<real;
}
else//当虚部小于0时
{
cout<<real<<imag<<'i';
}
}

int main( )
{
Complex<double> Cmp1(8,-2), Cmp2(7,10), Cmp3;

//两个复数相加
Cmp1.display();
cout<<" + ";
Cmp2.display();
cout<<" = ";
Cmp3 = Cmp1.complex_add(Cmp2);
Cmp3.display();
cout<<endl;

//两个复数相减
Cmp1.display();
cout<<" - ";
Cmp2.display();
cout<<" = ";
Cmp3 = Cmp1.complex_minus(Cmp2);
Cmp3.display();
cout<<endl;

//两个复数相乘
Cmp1.display();
cout<<" * ";
Cmp2.display();
cout<<" = ";
Cmp3 = Cmp1.complex_multiply(Cmp2);
Cmp3.display();
cout<<endl;

//两个复数相除
Cmp1.display();
cout<<" / ";
Cmp2.display();
cout<<" = ";
Cmp3 = Cmp1.complex_divide(Cmp2);
Cmp3.display();
cout<<endl;

system("pause");
}


执行结果:

使用模板类实现复数的四则运算