【问题标题】:Reducing negative fraction减少负分数
【发布时间】:2016-04-12 21:44:35
【问题描述】:

所以我在减少负分数方面有点问题

这是我的减少代码

private void reduce() {
    int g = Helper.gcd(this.num, this.den);

    num /= g;
    den /= g;
}

例如: 8/64 等于 1/8

但是给 -8/64 让我们的程序崩溃

这是我的 gcd 代码

public static int gcd(int a, int b) {
     while (a != b) {
        if (a > b) {
            a -= b;
        } else {
            b -= a;
        }
    }
    return a;
}

【问题讨论】:

  • 正如旁注:这样的代码对于单元测试来说真的是完美。这有一个很大的优势,即您可以直接跳到调试器中,以防您的某个测试失败。
  • 另一件小事:a 和 b 是变量的非常糟糕的名称。给你的东西起个名字来说明它们是什么。

标签: java reduce fractions


【解决方案1】:

您需要先提取符号。

private void reduce() {
    boolean neg = (num < 0) != (den < 0);
    num = Math.abs(num);
    den = Math.abs(den);
    // obtain the GCD of the non-negative values.
    int g = Helper.gcd(num, den);

    num /= g;
    den /= g;
    if (neg) num *= -1;
}

【讨论】:

    【解决方案2】:

    您的gcd 方法仅适用于正数。负数和零需要分开处理。

    public static int gcd(int a, int b) {
        a = Math.abs(a);
        b = Math.abs(b);
        if (a == 0) {
            if (b == 0)
                throw new IllegalArgumentException();
            return b;
        }
        if (b == 0)
            return a;
        // The rest is just your code, unchanged.
        while (a != b) {
            if (a > b) {
                a -= b;
            } else {
                b -= a;
            }
        }
        return a;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多