overloaded operator + takes two fractions
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
class Fraction
{
private int numerator;
private int denominator;
// create a fraction by passing in the numerator
// and denominator
public Fraction(int numerator, int denominator)
{
this.numerator=numerator;
this.denominator=denominator;
}
// overloaded operator + takes two fractions
// and returns their sum
public static Fraction operator+(Fraction lhs, Fraction rhs)
{
// like fractions (shared denominator) can be added
// by adding their numerators
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator+rhs.numerator,
lhs.denominator);
}
// simplistic solution for unlike fractions
// 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
// this method does not reduce.
int firstProduct = lhs.numerator * rhs.denominator;
int secondProduct = rhs.numerator * lhs.denominator;
return new Fraction(
firstProduct + secondProduct,
lhs.denominator * rhs.denominator
);
}
// return a string representation of the fraction
public override string ToString()
{
String s = numerator.ToString() + "/" +
denominator.ToString();
return s;
}
}
public class TesterOverrideToString
{
static void Main()
{
Fraction f1 = new Fraction(3,4);
Console.WriteLine("f1: {0}", f1.ToString());
Fraction f2 = new Fraction(2,4);
Console.WriteLine("f2: {0}", f2.ToString());
Fraction f3 = f1 + f2;
Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString());
}
}
Related examples in the same category