Programming Practice

寫一個 C++ 語言的程式專案定義一個複數的類別及複數的加法、減法、乘法、除法 、絕對值運算、讀取複數、設定複數,和輸出與輸入的友函式,如下:

 

friend ostream &operator<<(ostream &, const Complex &); // 複數輸出友函式

friend istream &operator>>(istream &, Complex &); // 複數輸入友函式

 

public:

 Complex(double = 0.0, double = 0.0); // 複數建構

 Complex(const Complex&); // 複數建構

 

 Complex operator+(const Complex) const; // 複數加法

 Complex operator-(const Complex) const; // 複數減法

 Complex operator*(const Complex) const; // 複數乘法

 Complex operator/(const Complex) const; // 複數除法

 double cabs(void) const; // 複數絕對值

 Complex& operator=(const Complex&); // 複數設定句

 bool operator==(const Complex&) const; // 複數相等

 bool operator!=(const Complex&) const; // 複數不等

 double getReal() const; // 讀取實部

 double getImage() const; // 讀取虛部

 void setComplex(const double, const double); // 設定複數

複數的運算如下所示:

  1. (a + b i) + (c + d i) = (a + c) + (b + d) i

  2. (a + b i) - (c + d i) = (a - c) + (b - d) i

  3. (a + b i) * (c + d i) = (a * c - b * d) + (a * d + b * c) i

  4. (a + b i) / (c + d i) = ((a * c + b * d) + (-a * d + b * c) i) /(c2 + d2)

  5. |a + bi| = (a2 + b2)1/2

複數專案頭檔及應用程式分別為 complex_arithmetics_class.h complex_arithmetics_class_app.cpp, 完成複數運算的實作檔 complex_arithmetics_class.cpp. 讀入兩個複數 a 和  b,並計算及輸出 (1) c = a + b, (2) a 和  b 兩個數相加、相減、相乘、相除、和 a 絕對值的結果; (3) 算術式  a+b*ca*b*b+c*a-a.

Enter complex number a (re + im): 2.5 3.2
Enter complex number b (re + im):
-1.2 -2.5

c = a+b is 1.3 + 0.7i
a = 2.5 + 3.2i
b = -1.2 - 2.5i
c = 1.3 + 0.7i

a+b = 1.3 + 0.7i
a-b = 3.7 + 5.7i
a*b = 5 - 10.09i
a/b = -1.43043 + 0.313394i
|a| = 4.06079

a+b*c = 2.69 - 0.89i
a*b*b+c*a-a = -32.715 + 2.318i