0
点赞
收藏
分享

微信扫一扫

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

you的日常 2022-04-13 阅读 70
c++
#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 条评论