Как я могу создать метод Java для упрощения дроби?

Я написал класс Fraction, и у меня проблемы с упрощением.

Когда я создаю объект Fraction, все работает нормально, я просто думаю, что моя логика запуталась с упрощением.

(число и ден являются частными переменными в классе для числителя и знаменателя соответственно)

Вот мои методы 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();
        }
    }
}

person ShanaBoo    schedule 19.02.2013    source источник
comment
Какой у Вас вопрос? У вас есть проблемы с этим кодом? Это не дает хороших результатов? Что вы ожидаете и что происходит?   -  person Cyrille Ka    schedule 19.02.2013
comment
Эй, @CyrilleKarmann, это не упрощает. Я ожидаю, что дробь вроде 20/5 войдет и станет 4. Или 18/4 станет 9/2.   -  person ShanaBoo    schedule 19.02.2013
comment
Понятно, но что это дает вместо того, что вы ожидаете?   -  person Cyrille Ka    schedule 19.02.2013
comment
@CyrilleKarmann выводится та же дробь, что и вводится.   -  person ShanaBoo    schedule 19.02.2013
comment
@CyrilleKarmann ПОПРАВКА:. вход: 15/3, выход: 3/3   -  person ShanaBoo    schedule 19.02.2013
comment
Разве this.den = num / gcd(); не должно быть this.den = den / gcd(); вместо этого?   -  person Cyrille Ka    schedule 19.02.2013


Ответы (1)


Две вещи, которые я вижу сразу: вы делите num на gcd() дважды, для каждого из числителя и знаменателя. Кроме того, если вы измените числитель, то результат вызова gcd() может измениться. Вызовите «gcd» один раз, сохраните результат и используйте его позже:

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

Кроме того, есть более эффективные способы получения наибольшего общего делителя: страница Википедии. См. Алгоритм Евклида на этой странице.

person rgettman    schedule 19.02.2013
comment
Спасибо за помощь. Я не совсем понимаю if(gcd). Что еще должно быть в скобках? Спасибо за помощь. - person ShanaBoo; 19.02.2013