Write complex code

 寫出複數程式碼


可寫為 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) {}


    Complex operator+(const Complex& other) const {

        return Complex(real + other.real, imag + other.imag);

    }


    Complex operator-(const Complex& other) const {

        return Complex(real - other.real, imag - other.imag);

    }


    Complex operator*(const Complex& other) const {

        return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);

    }


    Complex operator/(const Complex& other) const {

        if (other.real == 0.0 && other.imag == 0.0) {

            throw "Division by zero is not allowed.";

        }

        float denominator = other.real * other.real + other.imag * other.imag;

        return Complex((real * other.real + imag * other.imag) / denominator,

                       (imag * other.real - real * other.imag) / denominator);

    }

};


std::ostream& operator<<(std::ostream& os, const Complex& complex) {

    os << "(" << complex.real << "+" << complex.imag << "i)";

    return os;

}


int main() {

    Complex a(2, 3);

    Complex b(1, 1);


    Complex sum = a + b;

    Complex diff = a - b;

    Complex product = a * b;

    Complex quotient = a / b;


    std::cout << "a: " << a << std::endl;

    std::cout << "b: " << b << std::endl;

    std::cout << "a + b: " << sum << std::endl;

    std::cout << "a - b: " << diff << std::endl;

    std::cout << "a * b: " << product << std::endl;

    std::cout << "a / b: " << quotient << std::endl;


    return 0;

}

```


這個程式包括 Complex 類別,它具有成員變數 `real` 和 `imag` 用於表示複數的實部和虛部。程式碼還包括 `operator+`、`operator-`、`operator*` 和 `operator/` 用於實現四則運算。此外,它包括輸出操作子 `<<`,使複數可以用 `cout` 來輸出。


Comments

Popular posts from this blog

How to write data into a excel file using vbscript

Format date as yyyy-mm-dd using vbscript