Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I will need to order them from smallest to largest, so eventually I will need to represent them as a double also</p> </blockquote> <p>Not strictly necessary. (In fact if you want to handle equality correctly, don't rely on double to work properly.) If b*d is positive, a/b &lt; c/d if ad &lt; bc. If there are negative integers involved, that can be handled appropriately...</p> <p>I might rewrite as:</p> <pre><code>public int compareTo(Fraction frac) { // we are comparing this=a/b with frac=c/d // by multiplying both sides by bd. // If bd is positive, then a/b &lt; c/d &lt;=&gt; ad &lt; bc. // If bd is negative, then a/b &lt; c/d &lt;=&gt; ad &gt; bc. // If bd is 0, then you've got other problems (either b=0 or d=0) int d = frac.getDenominator(); long ad = (long)this.numerator * d; long bc = (long)this.denominator * frac.getNumerator(); long diff = ((long)d*this.denominator &gt; 0) ? (ad-bc) : (bc-ad); return (diff &gt; 0 ? 1 : (diff &lt; 0 ? -1 : 0)); } </code></pre> <p>The use of <code>long</code> here is to ensure there's not an overflow if you multiply two large <code>int</code>s. handle If you can guarantee that the denominator is always nonnegative (if it's negative, just negate both numerator and denominator), then you can get rid of having to check whether b*d is positive and save a few steps. I'm not sure what behavior you're looking for with zero denominator.</p> <p>Not sure how performance compares to using doubles to compare. (that is, if you care about performance that much) Here's a test method I used to check. (Appears to work properly.)</p> <pre><code>public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); int d = Integer.parseInt(args[3]); Fraction f1 = new Fraction(a,b); Fraction f2 = new Fraction(c,d); int rel = f1.compareTo(f2); String relstr = "&lt;=&gt;"; System.out.println(a+"/"+b+" "+relstr.charAt(rel+1)+" "+c+"/"+d); } </code></pre> <p>(p.s. you might consider restructuring to implement <code>Comparable</code> or <code>Comparator</code> for your class.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload