Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

C++複數類別加上計算乘除的函式

麻煩大大幫我改一下程式 感謝!

@請替http://christ756.googlepages.com/ch08-11.txt

的複數類別加上計算乘法和除法的函式。

@承上題,複數類別的成員函式只能做2個複數類別物件的計算,請用多載的方式,加上可作複數與double型別的計算。

1 Answer

Rating
  • Cloud
    Lv 4
    1 decade ago
    Favorite Answer

    Complex& multiple(const Complex& a)

    {

    double r, i;

    r = real * a.real;

    r -= image * a.image;

    i = real * a.image;

    i += image * a.real;

    real = r;

    image = i;

    return *this;

    }

    Complex& divide(const Complex& a)

    {

    double r, i, m;

    m = a.real * a.real + a.image * a.image;

    //分母用(x2+y2i)*(x2-y2i)公式使其成無只有實部的數。

    r = real * a.real;

    r += image * a.image;

    i = 0.0 - real * a.image;

    i += image * a.real;

    //分子為(x1+y1i) * (x2 - y2i)

    if( m != 0.0 )//預防除零錯誤

    {

    real = r / m;

    image = i / m;

    }

    return *this;

    }

    超載對double型別運算

    Complex& add(const double a) { real += a; return *this; }

    Complex& minus(const double a) {real -= a; return *this; }

    Complex& multiple(const double a) { real *= a; image *= a; return *this; }

    Complex& divide(const double a) {

    if(a!=0.0) {

    real /= a;

    image /= a;

    }

    }

    Source(s): 自己
Still have questions? Get your answers by asking now.