标准复数类

#include<iostream>
#include<string>
using namespace std;
template<typename T>class Complex{
    private:
         T Real;
         T Image;
    public:
    Complex(){
         Real=0;
         Image=0;
    }
    Complex(T a){
         Real=a;
    }
    Complex(T real,T image){
         Real=real;
         Image=image;
    }
    Complex operator+(Complex a);
    Complex operator-(Complex a);
    Complex operator*(Complex a);
    Complex operator/(Complex a);
    Complex operator=(Complex a);
    void print();
};
template<typename T>Complex<T>  Complex<T>::operator+(Complex a){
    Complex temp;
    temp.Real=Real+a.Real;
    temp.Image=Image+a.Image;
    return temp;
}
template<typename T>Complex<T> Complex<T>::operator-(Complex a){
    Complex temp;
    temp.Real=Real-a.Real;
    temp.Image=Image-a.Image;
    return temp;
}
template<typename T>Complex<T> Complex<T>::operator*(Complex a){
    Complex temp;
    temp.Real=Real*a.Real-Image*a.Image;
    temp.Image=Real*a.Image+Image*a.Real;
    return temp;
}
template<typename T>Complex<T> Complex<T>::operator/(Complex a){
    Complex temp;
    T num=a.Real*a.Real+a.Image*a.Image;
    temp.Real=(Real*a.Real+Image*a.Image)/num;
    temp.Image=(Image*a.Real-Real*a.Image)/num;
    return temp;
}
template<typename T>Complex<T> Complex<T>::operator=(Complex a){
    Real=a.Real;
    Image=a.Image;
    return *this;
}
template<typename T>void Complex<T>::print(){
    if(Image>0)
    cout<<Real<<"+"<<Image<<"i"<<endl;
    else cout<<Real<<Image<<"i"<<endl;
}
void main(){
    Complex<float> f;
    Complex<float> b;
    Complex<float> c;
    float x,y,m,n;
    char i;
    while(1){
       cout<<"输入第一个复数:(例如:0.0 3.4)"<<endl;
       cin>>x>>y;
       f=Complex<float>(x,y);
       cout<<"请输入第二个个复数:"<<endl;
       cin>>m>>n;
       b=Complex<float>(m,n);
       cout<<"输入你所需进行的运算:"<<endl;
       cin>>i;
       switch(i){
       case '+': c=f+b;c.print(); break;
       case '-': c=f-b;c.print(); break;
       case '*': c=f*b;c.print(); break;
       case '/': c=f/b;c.print(); break;
       default: cout<<"输入错误,请重新输入!"<<endl;}
       }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值