减少负分数

Reducing negative fraction

所以我在减少负分数方面遇到了一点问题

这是我的归约代码

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;
}

您需要先提取符号。

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;
}

您的 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;
}