Last active
October 17, 2024 05:35
-
-
Save fidelsoto/b4c0f14b800c58e137ad5757f35cacd6 to your computer and use it in GitHub Desktop.
Fraction Class C#. Supports formatting, comparing and simplifying fractions. In this code we can see the usage of constructors, operator overriding and helper functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Fraction | |
{ | |
public int numerator; | |
public int denominator; | |
public Fraction(int numerator, int denominator) | |
{ | |
this.numerator = numerator; | |
this.denominator = denominator; | |
} | |
public Fraction(Fraction fraction) | |
{ | |
numerator = fraction.numerator; | |
denominator = fraction.denominator; | |
} | |
public override bool Equals(object obj) | |
{ | |
Fraction other = obj as Fraction; | |
return (numerator == other.numerator && denominator == other.denominator); | |
} | |
public static bool operator ==(Fraction f1, Fraction f2) | |
{ | |
return f1.Equals(f2); | |
} | |
public static bool operator !=(Fraction f1, Fraction f2) | |
{ | |
return !(f1 == f2); | |
} | |
public override int GetHashCode() | |
{ | |
return numerator * denominator; | |
} | |
public override string ToString() | |
{ | |
return numerator + "/" + denominator; | |
} | |
//Helper function, simplifies a fraction. | |
public Fraction Simplify() | |
{ | |
for (int divideBy = denominator; divideBy > 0; divideBy--) | |
{ | |
bool divisible = true; | |
if ((int)(numerator / divideBy) * divideBy != numerator) | |
{ | |
divisible = false; | |
} | |
else if ((int)(denominator / divideBy) * divideBy != denominator) | |
{ | |
divisible = false; | |
} | |
else if (divisible) | |
{ | |
numerator /= divideBy; | |
denominator /= divideBy; | |
} | |
} | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's an even better version. Uses integral types as it should, handles overflow better, implements all the interfaces it should, has a better simplification algorithm, and has methods with friendly names so other languages without operator overloading can still use the class.