Posts

Showing posts with the label math

Write complex code

Image
 寫出複數程式碼 可寫為 a+bi 之數稱為複數(Complex Number),其中 a 與 b 均為實數,i 表示虛數, 亦即 i2 = -1。a 稱為複數的實部(real part),b 稱為複數的虛部(imaginary part)。 複數四則運算如下: ‧加法: idbcadicbia )()()()( +++=+++ ‧減法: idbcadicbia )()()()( −−−=+−+ ‧乘法: )( bia + ‧ ibcadbdacdic )()()( ++−=+ ‧除法: i dc adbd dc bdac dicdic dicbia dic bia 2222 )()( )()( + − + + + = −+ −+ = + + 請以 C++語言, 宣告 complex(複數)class,包含宣告為 float 型式之成員變數:實部(real)與虛部 (imag);將實部與虛部皆預設為 0.0 之建構子(constructor);可進行四則運算之成 員運算符(operator):+、 -、*、/;將實部與虛部各乘以 -1 之成員運算符 -。(10 分) 寫出於複數 class 外部,定義成員 operator *之程式碼。(5 分) 寫出於複數 class 外部,定義成員 operator /之程式碼。加入例外處理(exception handle)避免分母為 0。(10 分) 寫出定義 operator <<之程式碼,使得於主函式中可直接使用 cout<<將複數顯示於 螢幕為(real+imag i),例如:(2+3i)。(5 分 以下是 C++ 程式碼,包含 Complex(複數) 類別,實現複數的基本四則運算,包括加法、減法、乘法和除法,以及輸出操作子 `<<` 用於將複數顯示在螢幕上: ```cpp #include <iostream> class Complex { public:     float real;     float imag;     Complex(float real = 0.0, float imag = 0.0) : real(real), imag(imag) {}     Co...