阿摩線上測驗 登入

申論題資訊

試卷:103年 - 103年專門職業及技術人員高等建築師、技師、第二次食品技師暨普通不動產經紀人、記帳士考高等_資訊技師#29113
科目:程式設計
年份:103年
排序:0

題組內容

三、試以 C++來定義有理數(意即分數)類別 Rational 如下,其包含有分子 a 和分母 b,其
中分母 b 不能為 0。
class Rational {
private:
int a; // 分子
int b; // 分母
……
public:
……
};
假設 main( )的主程式,和其所執行輸出的結果如下:

申論題內容

⑴試列出完整的 Rational 類別定義。(10 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
下面是 Rational 類的一個可能的 C++ 定義。這個定義包括了構造函數、一個私有的簡化函數、運算符重載,以及 prt 函數來輸出 Rational 對象。
cpp
Copy code
#include <iostream>
#include <numeric>  // For std::gcd
class Rational {
private:
    int a;  // 分子
    int b;  // 分母
    // Helper function to reduce the fraction
    void reduce() {
        int gcd = std::gcd(a, b);  // Compute the greatest common divisor
        a /= gcd;  // Reduce the numerator by the gcd
        b /= gcd;  // Reduce the denominator by the gcd
    }
public:
    // Default constructor that initializes a rational number as 0/1
    Rational() : a(0), b(1) {}
    // Constructor that initializes the rational number with given numerator and denominator
    Rational(int numerator, int denominator) : a(numerator), b(denominator) {
        if (b == 0) {
            throw std::invalid_argument("分母不能為 0");
        }
        reduce();
    }
    // Prints the rational number in the format a/b
    void prt() const {
        std::cout << a << "/" << b;
    }
    // Overload the + operator
    Rational operator+(const Rational& rhs) const {
        return Rational(this->a * rhs.b + rhs.a * this->b, this->b * rhs.b);
    }
    // Overload the - operator
    Rational operator-(const Rational& rhs) const {
        return Rational(this->a * rhs.b - rhs.a * this->b, this->b * rhs.b);
    }
    // Overload the * operator
    Rational operator*(const Rational& rhs) const {
        return Rational(this->a * rhs.a, this->b * rhs.b);
    }
    // Overload the / operator
    Rational operator/(const Rational& rhs) const {
        if (rhs.a == 0) {
            throw std::invalid_argument("除數的分子不能為 0");
        }
        return Rational(this->a * rhs.b, this->b * rhs.a);
    }
};
int main() {
    Rational r0;
    std::cout << "r0 = "; r0.prt(); std::cout << std::endl;
    Rational r1(2, 4);
    std::cout << "r1 = "; r1.prt(); std::cout << std::endl;
    Rational r2(3, 6);
    std::cout << "r2 = "; r2.prt(); std::cout << std::endl;
    Rational r3 = r1 + r2;
    std::cout << "r1 + r2 = "; r3.prt(); std::cout << std::endl;
    Rational r4 = r1 - r2;
    std::cout << "r1 - r2 = "; r4.prt(); std::cout << std::endl;
    Rational r5 = r1 * r2;
    std::cout << "r1 * r2 = "; r5.prt(); std::cout << std::endl;
    Rational r6 = r1 / r2;
    std::cout << "r1 / r2 = "; r6.prt(); std::cout << std::endl;
    return 0;
}
這個類別的定義包括了為 Rational 提供基本運算的運算子重載,如加法、減法、乘法和除法。請注意,所有的運算都會在構造時自動進行約分,以確保結果是簡化後的形式。此外,該程式碼包括了錯誤檢查,以防止分母為零或在除法中除以零的情況。這個類別定義不包括從命令行讀取數值的代碼;您需要將這部分代碼添加到 main 函數中,或者創建一個單獨的函數來處理輸入。