2009年10月31日 星期六

Fix Point Number

 
Just for reference.
it's non-thread-safe and low-precision design.

struct Fixed
{
    static Fixed m;
    static const int M = 1<<sizeof(int)*4;
    int n;
    Fixed (float i) {n = int(i*M);}
    Fixed operator+ (Fixed f) {m.n = n+f.n; return m;}
    Fixed operator- (Fixed f) {m.n = n-f.n; return m;}
    Fixed operator* (Fixed f) {m.n = int(double(n)*f.n/M); return m;}
    Fixed operator/ (Fixed f) {m.n = int(double(n)*M/f.n); return m;}
    operator float() const {return float(n)/M;}
};

Fixed Fixed::m = 0;

int main ()
{
    Fixed a = 3.1415;
    Fixed b = 271.8281;
    #define _ <<endl<<
    cout _ a+b _ a-b _ a*b _ a/b;
}

沒有留言:

張貼留言