Make a Fraction class in C#

The class uses the following code, most of which is straightforward.

class Fraction
{
public long Numerator, Denominator;

// Initialize the fraction from a string A/B.
public Fraction(string txt)
{
string[] pieces = txt.Split('/');
Numerator = long.Parse(pieces[0]);
Denominator = long.Parse(pieces[1]);
Simplify();
}

// Initialize the fraction from numerator and denominator.
public Fraction(long numer, long denom)
{
Numerator = numer;
Denominator = denom;
Simplify();
}

// Return a * b.
public static Fraction operator *(Fraction a, Fraction b)
{
// Swap numerators and denominators to simplify.
Fraction result1 = new Fraction(a.Numerator, b.Denominator);
Fraction result2 = new Fraction(b.Numerator, a.Denominator);

return new Fraction(
result1.Numerator * result2.Numerator,
result1.Denominator * result2.Denominator);
}

// Return -a.
public static Fraction operator -(Fraction a)
{
return new Fraction(-a.Numerator, a.Denominator);
}

// Return a + b.
public static Fraction operator +(Fraction a, Fraction b)
{
// Get the denominators' greatest common divisor.
long gcd_ab = MathStuff.GCD(a.Denominator, b.Denominator);

long numer =
a.Numerator * (b.Denominator / gcd_ab) +
b.Numerator * (a.Denominator / gcd_ab);
long denom =
a.Denominator * (b.Denominator / gcd_ab);
return new Fraction(numer, denom);
}

// Return a - b.
public static Fraction operator -(Fraction a, Fraction b)
{
return a + -b;
}

// Return a / b.
public static Fraction operator /(Fraction a, Fraction b)
{
return a * new Fraction(b.Denominator, b.Numerator);
}

// Simplify the fraction.
private void Simplify()
{
// Simplify the sign.
if (Denominator < 0)
{
Numerator = -Numerator;
Denominator = -Denominator;
}

// Factor out the greatest common divisor of the
// numerator and the denominator.
long gcd_ab = MathStuff.GCD(Numerator, Denominator);
Numerator = Numerator / gcd_ab;
Denominator = Denominator / gcd_ab;
}

// Convert a to a double.
public static implicit operator double(Fraction a)
{
return (double)a.Numerator / a.Denominator;
}

// Return the fraction's value as a string.
public override string ToString()
{
return Numerator.ToString() + "/" + Denominator.ToString();
}
}

The Simplify method divides the greatest common divisor (GCD) from the numerator and the denominator. For a description of the GCD function, see the example Calculate the greatest common divisor (GCD) and least common multiple (LCM) of two integers in C#.

I'll leave it as an exercise to figure out why the * operator method makes two intermediate Fractions that mix the numerators and denominators of the operands.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.