1

我的 Rational 类应该加、减、乘和除分数,所以当在主类中调用时,它将执行这些操作。但是,我似乎无法正确减少分数(gcd)以获得正确的答案,并且除法方法根本没有运行(我收到一条错误消息):

线程“主”java.lang.ArithmeticException 中的异常:/在 Project1.main(Project1.java:12) 的 Rational.division(Project1.java:45) 处为零

我该如何解决这些问题?谢谢

公共类项目1 {

public static void main(String[] args) {

    Rational a = new Rational (6, 12);
    Rational b = new Rational (8, 9);

    System.out.println(a + " + " + b + " = " + a.add(b));
    System.out.println(a + " - " + b + " = " + a.subtraction(b));
    System.out.println(a + " * " + b + " = " + a.multiply(b));
    System.out.println(a + " / " + b + " = " + a.division(b));
}

}

类理性{

private int numerator, denominator;

public Rational(int num, int denom) {
    numerator = num;
    denominator = denom;
}
public Rational gcd() {
    while (numerator != denominator)
    {
        if (numerator > denominator)
            numerator = numerator - denominator;
        else
            denominator = denominator - numerator;
    }
    return new Rational(numerator, denominator);
}

public Rational add(Rational o) {
    return new Rational (numerator + o.numerator, denominator +o.denominator);
}

public Rational conjugate() {
    return new Rational (numerator, - denominator);
}

public Rational division(Rational o) {
    return new Rational ((numerator/denominator) / (numerator/denominator), denominator);
}

public Rational multiply(Rational o) {
    return new Rational (numerator * o.numerator, denominator * o.denominator);
}

public Rational subtraction(Rational o) {
    return new Rational (numerator - o.numerator, denominator - o.denominator);
}

public String toString() {
    return (numerator + "/" + denominator);
}

}

4

3 回答 3

1

你遇到的问题在这里:

public Rational division(Rational o) {
    return new Rational ((numerator/denominator) / (numerator/denominator), denominator);
}

当你运行你的代码时,你会:

(6/12)/(6/12)

括号中的两个 (6/12) 都被向下转换为 0,因此您最终会跳水 0,这是不允许的。

我建议使用 System.out.println() 调试代码,看看哪里出错了。但是错误很明显,您要除以0。

于 2016-10-20T17:41:49.173 回答
0

private int numerator, denominator;//这个值为0

与您使用的相同

public Rational division(Rational o) {
    return new Rational ((numerator/denominator) / (numerator/denominator), denominator);
}

代替object o

于 2016-10-20T17:45:23.520 回答
0

我会更改您的除法方法中的逻辑。您甚至不需要除以计算分数,这将避免您被零除的情况。相反,我会这样做来划分两个分数:

return new Rational (numerator * o.denominator, o.numerator * denominator);

另外,我并没有真正遵循 GCD 函数中的逻辑,因为我猜这会导致您陷入无限循环。如果需要帮助,请查阅 Euclid 算法。

于 2016-10-20T17:43:44.137 回答