Friday, October 9, 2009

Fractionally Better

Still working--or more honestly avoiding work--by working on the Fraction class. I found it much more complicated to overload the equality == operator than I thought it would be. First, you can't overload the == operator without also overloading the != operator. To make it work I also had to override the GetHash() method and the Equals() method. Though once I had done that, the operators were easy. It was also necessary to make sure I had a workable method to reduce the fraction, otherwise the comparison of say 1/2 to 2/4 would not return equal. Here are the methods

public static bool operator ==(Fraction f1, Fraction f2)
{

return f1.Equals(f2);
}

public static bool operator !=(Fraction f1, Fraction f2)
{


return !f1.Equals(f2);
}

public static Fraction Reduce(Fraction fr)
{
int i;
for (i=fr.Denominator;i>1;i--)
{
if(fr.Numerator % i ==0 && fr.Denominator % i == 0)
{
break;
}

}
fr.Numerator=fr.Numerator/i;
fr.Denominator=fr.Denominator/i;

return fr;
}




public override int GetHashCode()
{
return Numerator ^ Denominator;
}


public override bool Equals(object obj)
{
bool result=false;
if (obj == null)
result=false;

if (GetType() != obj.GetType())
result= false;

Fraction fr = (Fraction)obj;
fr = Reduce(fr);


Fraction fr2 = new Fraction(this.Numerator, this.Denominator);
fr2 = Reduce(fr2);

this.Numerator = fr2.Numerator;
this.Denominator = fr2.Denominator;

if (this.Numerator == fr.Numerator && this.Denominator == fr.Denominator)
{
result = true;
}

return result;
}


Now I just have the > and < operators to do, and to develop a good ToString method. I also want to overload the constructor.
As for the rest, I have been watering the lawn and looking forward to next weeks rain. The river poem flows on, approaching 20 pages.

No comments:

Post a Comment