implement divide static and instance method
This commit is contained in:
@@ -83,19 +83,24 @@ public class Rational {
|
|||||||
return r1.multiply(r2);
|
return r1.multiply(r2);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Instance method - this / other
|
// COMPLETED - Instance method - this / other
|
||||||
// Formula: (a/b) ÷ (c/d) = (a*d) / (b*c)
|
|
||||||
public Rational divide(Rational other) {
|
public Rational divide(Rational other) {
|
||||||
// YOUR CODE HERE
|
if (other.numerator == 0) {
|
||||||
// HINT: Division is multiplication by reciprocal
|
return null;
|
||||||
// Don't forget to check if other.numerator is zero!
|
}
|
||||||
return null; // Remove this line when implemented
|
|
||||||
|
int newNumerator = this.numerator * other.denominator;
|
||||||
|
int newDenominator = this.denominator * other.numerator;
|
||||||
|
|
||||||
|
Rational result = new Rational(newNumerator, newDenominator);
|
||||||
|
result.simplify();
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Static method - r1 / r2
|
// COMPLETED - Static method - r1 / r2
|
||||||
public static Rational divide(Rational r1, Rational r2) {
|
public static Rational divide(Rational r1, Rational r2) {
|
||||||
// YOUR CODE HERE
|
return r1.divide(r2);
|
||||||
return null; // Remove this line when implemented
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PROVIDED - String representation
|
// PROVIDED - String representation
|
||||||
|
|||||||
Reference in New Issue
Block a user