我的Rational Class应该对分数进行加,减,乘和除,所以当在Main Class中调用时,它将执行这些操作。但是,我似乎无法正确地减少我的分数(gcd)以获得正确答案,并且除法方法根本没有运行(我收到错误消息):
线程中的异常" main" java.lang.ArithmeticException:/ by零 在Rational.division(Project1.java:45) 在Project1.main(Project1.java:12)
我该如何解决这些问题?感谢
公共类Project1 {
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));
}
}
类Rational {
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);
}
}
答案 0 :(得分: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。
答案 1 :(得分:0)
我会改变你的除法中的逻辑。你甚至不需要除以计算分数,这将避免你除以零的情况。相反,我会这样做来划分两个分数:
return new Rational (numerator * o.denominator, o.numerator * denominator);
另外,我并没有真正遵循GCD功能中的逻辑,因为我猜这会导致你无限循环。如果你需要帮助,请查看Euclid的算法。
答案 2 :(得分:0)
private int numerator,denominator; //此值为0
与
中使用的相同public Rational division(Rational o) {
return new Rational ((numerator/denominator) / (numerator/denominator), denominator);
}
而不是object o