2019年2月10日 星期日

自訂運匴元的複數四則運算 c++ 程式碼

// z.c
#include <math.h>
#include <stdio.h>
#define nearZero   1e-9
struct Cpxnum { // 自訂的複數類型
    double r,i; // 實部與虛部
    Cpxnum(double x=0, double y=0){ r=x; i=y;}//建構式
    Cpxnum operator + (Cpxnum other) { // 加法
        double x = r + other.r;
        double y = i + other.i;
        return  Cpxnum(x,y);
    }   
    Cpxnum operator - (Cpxnum other) { // 減法
        double x = r - other.r;
        double y = i - other.i;
        return  Cpxnum(x,y);
    }
    Cpxnum operator * (Cpxnum other) { // 乘法
        double x = r * other.r - i * other.i;
        double y = r * other.i + i * other.r;
        return  Cpxnum(x,y);
    }
    Cpxnum operator / (Cpxnum other) { // 除法
        double den = other.r * other.r + other.i * other.i ;
        if( den > nearZero ) { // to prevent divided by zero, other's length must be larger than 0 !!
          double x = (r * other.r + i * other.i)/den;
          double y = (i * other.r - r * other.i)/den;
          return  Cpxnum(x,y);
        }
        return Cpxnum(0,0); // TODO: raise an exception!!
    }
    void dump(){ // 列印複數實部加虛部
        if( abs(r) <= nearZero )       printf("%+fi\n",i);
        else if( abs(i) <= nearZero )  printf("%+f\n",r);      
        else                          printf("%+f + %fi\n",r,i);
    }
};
int main(){
    Cpxnum a = Cpxnum(1,3); // a = 1 + 3i
    Cpxnum b = Cpxnum(2,3); // b = 2 + 3i
    (a + b) . dump();
    (a - b) . dump();
    (a * b) . dump();
    (a / b) . dump();
}
用 g++ 編譯並執行  g++ z.c && ./a.out
+3.000000 + 6.000000i
-1.000000
-7.000000 + 9.000000i
+0.846154 + 0.230769i


沒有留言: