这是我计算有理数不同运算的代码。现在,我的任务是实施额外的安全措施assert
以防止溢出。我试图做一些事情,但是当我启用-ea
对 JVM 的断言时,它开始一直“抛出”断言(即使有4 > 5
断言条件)。我如何实现这一点以及在 Long
数字上做这件事的正确方法是什么?
public class Rational {
private final long numerator;
private final long denominator;
private double result;
public Rational(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
result = (double)numerator/(double)denominator;
}
public Rational plus(Rational b){
assert this.denominator * b.denominator >= Long.MAX_VALUE : "Overflow of denominator in 'PLUS'"; //My attempt
long plusDenominator = this.denominator * b.denominator;
long plusNumerator = ((plusDenominator / this.denominator) * this.numerator) + ((plusDenominator / b.denominator) * b.numerator);
long gcd = gcd(plusNumerator, plusDenominator);
return new Rational(plusNumerator / gcd, plusDenominator / gcd);
}
public Rational minus(Rational b){
long minusDenominator = this.denominator * b.denominator;
long minusNumerator = ((minusDenominator / this.denominator) * this.numerator) - ((minusDenominator / b.denominator) * b.numerator);
long gcd = gcd(minusNumerator, minusDenominator);
return new Rational(minusNumerator / gcd, minusDenominator / gcd);
}
public Rational times(Rational b){
long timesDenominator = this.denominator * b.denominator;
long timesNumerator = this.numerator * b.numerator;
long gcd = gcd(timesDenominator, timesNumerator);
return new Rational(timesNumerator / gcd, timesDenominator / gcd);
}
public Rational divides(Rational b){
long divDenominator = this.denominator * b.numerator;
long divNumerator = this.numerator * b.denominator;
long gcd = gcd(divNumerator, divDenominator);
return new Rational(divNumerator / gcd, divDenominator / gcd);
}
private long gcd(long p, long q){
if(q == 0) return p;
long r = p % q;
return gcd(q, r);
}
public static void main(String[] args){
Rational r1 = new Rational(8, 999999999999999999L);
Rational r2 = new Rational(8 ,999999999999999999L);
System.out.println(r1.plus(r2));
}
}