【问题标题】:How can I make a Java method for simplifying a fraction?如何制作简化分数的 Java 方法?
【发布时间】:2013-02-19 18:42:17
【问题描述】:

我写了一个分数类,但在简化时遇到了麻烦。

当我制作 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();
        }
    }
}

【问题讨论】:

  • 您的问题是什么?这段代码有问题吗?它没有给出好的结果?您期望什么以及正在发生什么?
  • 嘿@CyrilleKarmann,这不是简化。我期待像 20/5 这样的分数进入并变成 4。或者 18/4 变成 9/2。
  • 我明白了,但它提供的是什么而不是您期望的价值?
  • @CyrilleKarmann 输出的分数与放入的分数相同。
  • @CyrilleKarmann 更正:。输入:15/3,输出:3/3

标签: java simplify fractions


【解决方案1】:

我马上看到两件事:您将num 除以gcd() 两次,分别是分子和分母。此外,一旦您更改了分子,那么对gcd() 的调用结果可能会发生变化。调用“gcd”一次,存储结果,稍后使用:

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

此外,还有更有效的获取最大公约数的方法:Wikipedia's page。请参阅该页面上的 Euclid 算法。

【讨论】:

  • 感谢您的帮助。我不太明白 if(gcd)。括号中是否应该包含其他内容?感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2011-07-14
  • 1970-01-01
  • 2012-12-09
  • 2011-09-26
  • 1970-01-01
相关资源
最近更新 更多