HELP: make calculator program to calculate fractions!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • frozenfirefly
    New Member
    • Aug 2008
    • 1

    HELP: make calculator program to calculate fractions!

    okay, so the first class of this program is the Fraction class.
    and which I supposed to create:
    1. method to input numerator & denominator of fraction
    2. and a method to reduce the fraction to its smallest stage.
    example:
    input: 6/8
    reduce to: 3/4 (both are devided by the gcd which is 2)
    I think the problem is around the reduce method... about the gcd.
    please tell me what's wrong.

    [PHP]public class Fraction
    {
    // num: numerator of fraction, den: denominator of fraction
    private int num;
    private int den;

    /**
    * Constructor for objects of class fraction
    */
    public Fraction()
    {
    //default constructor (1/1)
    num = 1;
    den = 1;
    }

    /**
    * With num =1 and den = 2 it will return "1/2"
    *
    * @return A fraction constructed of numerator and denominator
    */

    public String toString()
    {
    //returning a string of the fraction showing numerator over denominator
    return num + "/" + den;
    }

    public int getNum () //accessor method, returns the value of the numerator
    {
    return num;
    }

    public int getDen ()//accessor method, returns the value of the denominator
    {
    return den;
    }


    public void setFraction (int inNum, int inDen) //mutator method, reassigns the values of the numerator & denominator
    {
    num = inNum;
    den = inDen;
    }


    public void reduce ()
    {
    int gcd =1;
    int x;

    if ( num < den )
    {
    x=num;
    }
    else
    {
    x=den;
    }

    while ( !((num%gcd)==0) && ((den%gcd)==0) )
    {
    x--;
    gcd = x;
    }
    num = num / gcd;
    den = den / gcd;
    }

    }[/PHP]

    thanks.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    A handy algorithm for finding GCDs is the Euclidean algorithm.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Just a few tips: make that class immutable and don't make that gcd() method
      a public method. If a user wants another fraction she should create a new one
      and not fiddle with another fraction. After your test class works properly change
      the int numerator and int denominator to BigIntegers. That default constructor
      isn't of much use, i.e. new Fraction(1, 1) isn't much more typing. Only store
      normalized fractions, i.e. the constructor should deal with the (private) gcd()
      method and store normalized numerators and denominators.

      kind regards,

      Jos

      Comment

      Working...