0

分数クラスを作成しましたが、簡略化に問題があります。

Fractionオブジェクトを作成すると、すべてが正常に機能します。単純化すると、ロジックが乱雑になると思います。

(numとdenは、それぞれ分子と分母のクラスのプライベート変数です)

これが私のGCDとSimplifyの方法です:

/**
 * Returns the absolute value of the greatest common divisor of this
 * fraction's numerator and denominator. If the numerator or denominator is
 * zero, this method returns 0. This method always returns either a positive
 * integer, or zero.
 * 
 * @return Returns the greatest common denominator
 */
private int gcd() {
    int s;
    if (num > den)
        s = den;
    else
        s = num;
    for (int i = s; i > 0; i--) {
        if ((num % i == 0) && (den % i == 0))
            return i;
    }
    return -1;
}

/**
 * Changes this fraction's numerator and denominator to "lowest terms"
 * (sometimes referred to as a "common fraction"), by dividing the numerator
 * and denominator by their greatest common divisor. This includes fixing
 * the signs. For example, if a fraction is 24/-18, this method will change
 * it to -4/3. If the numerator or denominator of the fraction is zero, no
 * change is made.
 */
public void simplify() {

    if (isZero() == false) {// Making sure num or den is not zero.
        this.fixSigns(); // Fix signs first

        if (gcd() > 1) {
            this.num = num / gcd();
            this.den = num / gcd();
        }
    }
}
4

1 に答える 1

2

すぐにわかる 2 つのこと:分子と分母のそれぞれについて、2 で割っnumています。gcd()また、一度分子を変更すると、呼び出しの結果gcd()が変わる場合があります。"gcd" を 1 回呼び出し、その結果を保存し、後で使用します。

int gcd = gcd();
if (gcd > 1) {
   this.num = this.num / gcd;
   this.den = this.den / gcd;
}

さらに、最大公約数を取得するより効率的な方法があります:ウィキペディアのページ. そのページの Euclid のアルゴリズムを参照してください。

于 2013-02-19T18:50:26.807 に答える