第九周C++实验报告(一)
来源:互联网 发布:张湘艳精准医学大数据 编辑:程序博客网 时间:2024/05/17 08:19
- #include<iostream.h>
- class Complex
- {
- public:
- Complex(){real=0;imag=0;}
- Complex(double r,double i){real=r;imag=i;}
- Complex operator+(Complex &c2);
- Complex operator-(Complex &c2);
- Complex operator*(Complex &c2);
- Complex operator/(Complex &c2);
- friend ostream& operator << (ostream&,Complex&);
- friend istream& operator >> (istream&,Complex&);
- private:
- double real;
- double imag;
- };
-
- istream& operator >> (istream& input,Complex& c)
- {
- input>>c.real>>c.imag;
- return input;
- }
-
- ostream &operator << (ostream &output,Complex &c)
- {
- output<<"("<<c.real<<" "<<c.imag<<"i)"<<endl;
- return output;
- }
-
- Complex Complex::operator+(Complex &c2)
- {
- Complex c;
- c.real=real+c2.real;
- c.imag=imag+c2.imag;
- return c;
- }
-
- Complex Complex::operator-(Complex &c2)
- {
- Complex c;
- c.real=real-c2.real;
- c.imag=imag-c2.imag;
- return c;
- }
-
- Complex Complex::operator*(Complex &c2)
- {
- Complex c;
- c.real=real*c2.real-imag*c2.imag;
- c.imag=imag*c2.real+real*c2.imag;
- return c;
- }
-
- Complex Complex::operator/(Complex &c2)
- {
- Complex c;
- double d=c2.real*c2.real+c2.imag*c2.imag;
- c.real=(real*c2.real+imag*c2.imag)/d;
- c.imag=(imag*c2.real-real*c2.imag)/d;
- return c;
- }
-
- int main()
- {
- Complex c1,c2,c3;
- cout<<"请输入复数c1的值:(以a b的形式输入)";
- cin>>c1;
- cout<<"请输入复数c2的值:(以a b的形式输入)";
- cin>>c2;
- cout<<"c1=";
- cout<<c1;
- cout<<"c2=";
- cout<<c2;
- c3=c1+c2;
- cout<<"c1+c2=";
- cout<<c3;
- c3=c1-c2;
- cout<<"c1-c2=";
- cout<<c3;
- c3=c1*c2;
- cout<<"c1*c2=";
- cout<<c3;
- c3=c1/c2;
- cout<<"c1/c2=";
- cout<<c3;
- return 0;
- }