Bladeren bron

(feat) Lab 6 Exercise 7 - double division

Implements an object type - DoubleDivisionResult class to return quotient and remainder
main
Rob Hallam 1 jaar geleden
bovenliggende
commit
ae5b69fdc5
1 gewijzigde bestanden met toevoegingen van 75 en 0 verwijderingen
  1. +75
    -0
      week1.java

+ 75
- 0
week1.java Bestand weergeven

@@ -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
*/


Laden…
Annuleren
Opslaan