头歌实训项目【复数运算】

阅读 71

2022-04-13

#include <iostream>  
using namespace std;
class Complex  
{    
    private:  
        float real;  
        float image;  
    public:  
        Complex(float r,float i);  
        void Print();  
        Complex operator+(Complex &c2);   
        Complex operator-(Complex &c2);  
        Complex operator*(Complex &c2);  
};    
Complex::Complex(float r,float i):real(r),image(i){}
void Complex::Print()  
{  
    if(image >= 0)  
        cout << real << "+" << image << "i" << endl;   
    else  
        cout << real << image << "i" << endl;  
}
Complex Complex::operator+(Complex &c2)  
{  
    return Complex(real + c2.real,image + c2.image);  
}
Complex Complex::operator-(Complex &c2)  
{  
    return Complex(real - c2.real,image - c2.image);  
}
Complex Complex::operator*(Complex &c2)  
{  
    return Complex(real * c2.real - image * c2.image,real * c2.image + image * c2.real); 
}  
int main()
{
	float a,b,c,d;
	cin >> a >> b >> c >> d;
    Complex c1(a,b),c2(c,d);

	cout << "c1 = ";
	c1.Print();
	cout << "c2 = ";
	c2.Print();

	cout << "c1 + c2 = ";
    (c1 + c2).Print();
	cout << "c1 - c2 = ";
    (c1 - c2).Print();
	cout << "c1 * c2 = ";
    (c1 * c2).Print();
}

精彩评论(0)

0 0 举报