第六周项目6 虚数

本文介绍了使用模板类实现复数的加、减、乘、除运算,包括不同类型的复数(整型、浮点型)操作,并展示了如何在主函数中调用这些运算方法。
#include <iostream>

using namespace std;

template <class numtype>
class Complex
{
private:
    numtype real,img;
public:
    Complex ()
    {
        real=0;
        img=0;
    }
    Complex(numtype r,numtype i)
    {
        real=r;    //类声明中的每一个T,将被对象定义时提供的实际类型代替
        img=i;
    }
    Complex complex_add(Complex &);
    Complex complex_minu(Complex &);
    Complex complex_multiply(Complex &);
    Complex complex_divide(Complex &);
    void display();
};
template<class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex &c1)
{
    Complex c;
    c.real=real+c1.real;
    c.img=img+c1.img;
    return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_minu(Complex &c1)
{
    Complex c;
    c.real=real-c1.real;
    c.img=img-c1.img;
    return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_multiply(Complex &c1)
{
    Complex c;
    c.real=real*c1.real+img*c1.img;
    c.img=real*c1.img+img*c1.real;
    return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_divide(Complex &c1)
{
    Complex c;
    numtype d=c1.real*c1.real+c1.img*c1.img;
    c.real=(real*c1.real+img*c1.img)/d;       //此处有危险未排除:除法溢出
    c.img=(img*c1.real-real*c1.img)/d;

    return c;
}
template<class numtype>
void Complex<numtype>::display()
{
    cout<<"("<<real<<","<<img<<"i)"<<endl;
}
int main( )
{
    Complex<int> c1(3,4),c2(5,-10),c3;   //实部和虚部是int型
    c3=c1.complex_add(c2);
    cout<<"c1+c2=";
    c3.display( );
    Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6; //实部和虚部是double型
    c6=c4.complex_add(c5);
    cout<<"c4+c5=";
    c6.display( );
    //下面测试减法、乘法和除法
    Complex<int> c7(3,4),c8(5,-10),c9;
    cout<<"c7-c8=";
    c9=c7.complex_minu(c8);
    c9.display();
       Complex<int> c10,c11;
    cout<<"c1*c2=";
    c10=c1.complex_multiply(c2);
    c10.display();
    cout<<"c7-c8=";
    c11=c1.complex_divide(c2);
    c11.display();
    return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值