Working with fractions in C# can be simplified using the `Fraction` class, which allows you to represent a fraction as a numerator and a denominator. Additionally, precision is crucial, especially when dealing with mathematical operations. Below is an example of a custom `Fraction` class that ensures proper handling of fractions and maintains precision.
// C# example of a simple Fraction class
public class Fraction
{
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public Fraction(int numerator, int denominator)
{
if (denominator == 0)
throw new ArgumentException("Denominator cannot be zero.");
Numerator = numerator;
Denominator = denominator;
Reduce();
}
private void Reduce()
{
int gcd = GCD(Numerator, Denominator);
Numerator /= gcd;
Denominator /= gcd;
}
private int GCD(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return Math.Abs(a);
}
public override string ToString()
{
return $"{Numerator}/{Denominator}";
}
}
// Usage example
var fraction = new Fraction(3, 9);
Console.WriteLine(fraction); // Outputs: 1/3
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?