Classes and operator overload
!~
using System;
class Fraction
{
int wholeNumber;
int numerator;
int denominator = 1;
public int WholeNumber
{
get{ return wholeNumber; }
set{ wholeNumber = value; }
}
public int Numerator
{
get{ return numerator; }
set{ numerator = value; }
}
public int Denominator
{
get{ return denominator; }
set{ denominator = (value != 0) ? value : 1; }
}
public Fraction(int wholeNumber, int numerator, int denominator)
{
this.wholeNumber = wholeNumber;
this.numerator = numerator;
this.Denominator = denominator; // use the property to validate here
}
public Fraction(int numerator, int denominator)
{
this.wholeNumber = 0;
this.numerator = numerator;
this.Denominator = denominator; // use the property to validate here
}
public Fraction()
{
this.wholeNumber = 0;
this.numerator = 0;
this.denominator = 1;
}
public void Reduce()
{
if (numerator == 0)
{
denominator = 1;
return;
}
int gcd = GetGCD(Math.Abs(numerator), Math.Abs(denominator));
numerator /= gcd;
denominator /= gcd;
}
public override string ToString()
{
return String.Format("{0} {1}/{2}", wholeNumber, numerator, denominator);
}
public static Fraction operator +(Fraction f1, Fraction f2)
{
f1.numerator += f1.wholeNumber * f1.denominator;
f1.wholeNumber = 0;
f2.numerator += f2.wholeNumber * f2.denominator;
f2.wholeNumber = 0;
int commonDenom = f1.denominator * f2.denominator;
f1.numerator *= f2.denominator;
f2.numerator *= f1.denominator;
f1.denominator = commonDenom;
f2.denominator = commonDenom;
Fraction f3 = new Fraction(f1.numerator + f2.numerator, commonDenom);
f3.Reduce();
if (Math.Abs(f3.numerator) >= Math.Abs(f3.denominator))
{
f3.wholeNumber += f3.numerator / f3.denominator;
f3.numerator = f3.numerator % f3.denominator;
if (f3.numerator == 0) f3.denominator = 1;
}
return f3;
}
static int GetGCD(params int[] numbers)
{
// get the smallest number as the GCD can't be larger than that
Array.Sort(numbers);
int min = numbers[0];
if (min < 1) throw new ArgumentException("The array can't include a number less than 1");
if (min == 1) return 1; // GCD must be 1
for(int i = min; i >= 1; i--)
{
int rem = min % i;
if (rem > 0) continue; // 'i' can't be a factor of min
bool isFactor = true;
for(int j = 1; j < numbers.Length; j++)
{
int rem2 = numbers[j] % i;
if (rem2 > 0) // 'i' can't be a factor of numbers[j]
{
isFactor = false;
break;
}
}
if (isFactor) return i; // 'i' must be the GCD
}
return 1; // needed to keep compiler happy, but will never get to this line
}
}
class FractionDemo
{
static void Main()
{
Fraction f1 = new Fraction(12, 24);
Console.Write("f1 = ");
Console.WriteLine(f1);
f1.Reduce();
Console.Write("f1 now = ");
Console.WriteLine(f1);
Fraction f2 = new Fraction(4, 8, 16);
Console.Write("f2 = ");
Console.WriteLine(f2);
f2.Reduce();
Console.Write("f2 now = ");
Console.WriteLine(f2);
Fraction f3 = f1 + f2;
Console.Write("f3 = f1 + f2 = ");
Console.WriteLine(f3);
Console.ReadKey();
}
}