我的 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);
}
}