第9周--項目1-Complex類

/*
* Copyright (c) 2011, 煙臺大學計算機學院
* All rights reserved.
* 作    者:王靜
* 完成日期:2013  年 5  月 5 日
* 版 本 號:v1.0
* 輸入描述:
* 問題描述:定義Complex類中的<<和>>運算符的重載,實現輸入和輸出,
      改造原程序中對運算結果顯示方式,使程序讀起來更自然。
* 程序輸出:
* 問題分析:
* 算法設計:略
*/
#include <iostream>
#include <Cstring>
using namespace std;
class Complex
{
public:
 Complex( ){real=0;imag=0;}
 //Complex(double r,double i){real=r;imag=i;}
 friend Complex operator+(Complex &c1,Complex &c2);
 friend Complex operator-(Complex &c1,Complex &c2);
 friend Complex operator*(Complex &c1,Complex &c2);
 friend Complex operator/(Complex &c1,Complex &c2);
 friend istream& operator>>(istream &cin,Complex&c);
 friend ostream& operator<<(ostream &cout,Complex&c);
private:
 double real;
 double imag;
};

Complex operator+(Complex &c1,Complex &c2)
{
 Complex c;
 c.real=c1.real+c2.real;
 c.imag=c1.imag+c2.imag;
 return c;
}
Complex operator-(Complex &c1,Complex &c2)
{
 Complex c;
 c.real=c1.real-c2.real;
 c.imag=c1.imag-c2.imag;
 return c;
}
Complex operator*(Complex &c1,Complex &c2)
{
 Complex c;
 c.real=c1.real*c2.real-c1.imag*c2.imag;
 c.imag=c1.imag*c2.real+c1.real*c2.imag;
 return c;
}
Complex operator/(Complex &c1,Complex &c2)
{
 Complex c;
 c.real=(c1.real/c2.real+c1.imag/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
 c.imag=(c1.imag/c2.real-c1.real/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
 return c;
}
istream & operator>>(istream&cin,Complex&c)
{
    cout<<"請輸入複數的實部與虛部"<<endl;
    cin>>c.real>>c.imag;
    return cin;
}
ostream & operator<<(ostream &cout,Complex&c)
{
    cout<<"(";
    cout<<c.real;
    cout<<","<<c.imag<<"i)"<<endl;
    return cout;
}
int main( )
{
 Complex c1,c2,c3;
 cin>>c1>>c2;
 cout<<c1<<c2<<endl;
 c3=c1+c2;
 cout<<"c1+c2="<<c3<<endl;
        c3=c1-c2;
 cout<<"c1-c2="<<c3<<endl;
 c3=c1*c2;
 cout<<"c1*c2="<<c3<<endl;
        c3=c1/c2;
 cout<<"c1/c2="<<c3<<endl;
 //system("pause");
 return 0;
}


 

運行結果:
(貼圖)

心得體會:


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章