From ae5b69fdc55fce7c02738a7f0d009b6f3ba08d8f Mon Sep 17 00:00:00 2001 From: Rob Hallam <0504004h@student.gla.ac.uk> Date: Tue, 19 Sep 2023 20:44:24 +0100 Subject: [PATCH] (feat) Lab 6 Exercise 7 - double division Implements an object type - DoubleDivisionResult class to return quotient and remainder --- week1.java | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/week1.java b/week1.java index d8b1bc4..f8f54ff 100644 --- a/week1.java +++ b/week1.java @@ -251,6 +251,7 @@ class Lab6 extends Lab { new six3(); new six5(); new six6(); + new six7(); } /** @@ -303,6 +304,80 @@ class Lab6 extends Lab { } } + class six7 extends Section { + public six7() { + super(7); + describeDD(4.2, 1.6); + describeDD(47.42, 7.9); + } + + /** Simple exposition of double division + * @param num1 Dividend + * @param num2 Divisor + */ + public void describeDD(double num1, double num2) { + System.out.println(String.format("Double division of %.2f by %.2f:\t", num1, num2)); + DoubleDivisionResult result = doubleDivision(num1, num2); + System.out.println(String.format("Quotient: %d (ie %.2f ✕ %d = %.2f)\tRemainder: %.2f", + result.getQuotient(), + num2, + result.getQuotient(), + (num2 * result.getQuotient()), + result.getRemainder())); + } + } + + /* TOASK - is there a better way of returning multiple values in Java? + à la python, ie: return (quotient, remainder) + */ + + /** + * Wrapper class for returning results from double division + */ + final class DoubleDivisionResult { + private int quotient; // that's the number of times something goes into something else + private double remainder; // that's the bit left over + + public DoubleDivisionResult(int quotient, double remainder) { + this.quotient = quotient; + this.remainder = remainder; + } + + public int getQuotient() { + return quotient; + } + + public double getRemainder() { + return remainder; + } + + } + + /** + * Perform 'double division' + * + * @param dividend Number to be divided + * @param divisor Number to divide by + * @return a {@link DoubleDivisionResult} with the (int) quotient and (double) remainder + */ + public DoubleDivisionResult doubleDivision(double dividend, double divisor) { + // example used is 4.2 and 1.6 + // should return 2 and 1.0 + final boolean DEBUG = false; + double dQuotient = dividend / divisor; + int iQuotient = (int)dQuotient; + + double remainder = dividend - (iQuotient * divisor); + + if (DEBUG) { + System.out.println(String.format("float quotient: %.2f", dQuotient)); + System.out.println(String.format("int quotient: %d", iQuotient)); + // TOASK: is there a neater way to do this casting? + } + + return new DoubleDivisionResult(iQuotient, remainder); + } + /** * @param num Size of triangle */