close

有時你會發現float(浮點數)不怎麼好用,也許會考慮用分數(Fraction)來處理問題。
本文的僅作引導,並不會列出完整原始碼

分數自然有分子(Numerator)和分母(Denominator),最起碼要能作加減乘除。在運算過程中我們需要進行擴分,此外求最簡分數須要約分,所以我們會需要輾轉相除法(Euclidean Alogorithm)來求最大公因數(Greatest Common Divisor)。
基於上述,我們可以寫出一個fraction.hpp來定義這個類別並宣告所需函式:

class Fraction
{
    private:
        int _Numerator;
        int _Denominator;

        int Euclidean_Alogorithm(int a, int b);
    public:
    //Constructor
        Fraction(int numerator = 1, int denominator = 1);
    //End
    //Define the operator

        Fraction operator+(Fraction that);
        Fraction operator-(Fraction that);
        Fraction operator*(Fraction that);
        Fraction operator/(Fraction that);

        bool operator==(Fraction that);

        Fraction operator-();
        Fraction Switch();//_Numerator/_Denominator into _Denominator/_Numerator
    //End
}

首先,我們要弄出一個分數,得要給他設定個初始值。用int會比較簡單;string需要考慮許多形式,如:1.9、1/2、1+1/8、循環小數,顯得比較複雜,後面會討論。

再來看到運算部份。看到我排列的方式,我想你知道前面四個是四則運算"加減乘除"。
中間單獨的傢伙是判斷兩個分數是否相等。
最後兩個。一個是乘上-1,另一個是轉成倒數。

輸入輸出

我們還欠缺一些輸入輸出的方式。像是最常被使用的cin
friend std::istream& operator>>(std::istream& in, Fraction& that);

std::istream& operator>>(std::istream& in, Fraction& that)
{
    return in >> that._Numerator >> that._Denominator;
}

這方法有點簡陋,想用如1.2這樣的形式輸入,得先輸入string後再將之轉成Fraction。為此,要設計新的constructor:

Fraction::Fraction(std::string str)
{
    //Does the string have a -

    //Find the site of . in the string

    //Get the part of numerator
    
    //Get the part of denominator
    
//Ex : 1.99; numerator is 199. the part after float point is 99. denominator is 100.
}

一開始判斷正負號。再來就是小數點或是除號的位置判斷,可以考慮多個帶分數形式的判斷。

輸入搞定了,換輸出。看過cin之後,cout也很簡單

std::ostream& operator<<(std::ostream& out, Fraction& that)
{
    return out << that._Numerator << "/" << that._Denominator;
}

一樣的道理,先轉成string再輸出會比較好,不過這部份會比輸入複雜。C/C++沒有提供string轉int的方式。另外,要轉成1.2這樣的形式要判斷分母是否只有2和5組成。

std::string int_to_str(long int num)
{
    std::queue<int> get_num;//#include <queue>. You can open stl_queue.h to look up how to use it!

    long int divider = 1000000000;//On 32bits OS the largerest value of "long int" is 2^32

    //if(num < 0)

    //push number to the queue

    //input number
}

int num_of_divisor(long int num, int divisor)
{
    //Get the number of divisor requested by you in specify number
}

Fraction::operator std::string()
{
    //if(_Numerator < 0)
    
    //if(_Numerator >= _Denominator)
    
    //In put the number after .
        
        //if( way == 1 )
            //way1
            //ex : 1.2
        //else
            //way2
            //ex : 1/2

}

寫程式的過程中會遇到許多問題,尤其是提示少的時候。我希望這能讓各位勇於專研和討論遇到的問題。

英文不好,不過為了讓註解在各個電腦上都能正常顯示,自然是要打英文。有錯誤的地方請多加指出。
另外,何時要call by reference(傳參呼叫)我不太清楚,所以都用call by value(傳值呼叫)。

P.S.    最近家裏的網路要重新簽約,請去多多煩社團幹部。

arrow
arrow
    全站熱搜

    liandy 發表在 痞客邦 留言(0) 人氣()