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.
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.
Comment