
.NET 1.1+Rational Number Arithmetic (2)
Standard arithmetic uses integers or floating-point values for operands and results. Rational numbers, or fractions, are not amongst the standard data types. In this article, we will create a structure for fractions and add arithmetic functionality.
Adding the Constructor
A single constructor will be responsible for setting the values of the numerator and denominator. Add the following constructor code:
public RationalNumber(int numerator, int denominator)
{
if (denominator == 0)
throw new ArgumentException("The denominator must be non-zero.");
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
_numerator = numerator;
_denominator = denominator;
ReduceToLowestTerms();
}
The constructor performs four key processes. Firstly, the denominator is validated to ensure that it is not zero. If a zero were permitted, the value of the entire fraction would always be infinity and trying to evaluate this value would cause a division by zero exception.
Once validated, the denominator is checked to determine if it is negative. Although it would be quite acceptable to have a negative denominator, it is more usual to express a fraction with a positive one. To achieve this, if the denominator is negative, both it and that numerator are multiplied by -1. This does not change the overall value of the fraction, just its representation.
The third stage is to store the numerator and denominator in the backing store fields for their respective properties. Once stored, the ReduceToLowestTerms method is called. This method is described below.
Reducing the Fraction to its Lowest Terms
A single rational number may be expressed as many different fractions. For example, one half (½) may be written with a numerator of two and a denominator of four, or as 4/8 or 5/10. Each of these representations is valid but generally it is preferred to show a fraction in its lowest terms. This means that the numerator and denominator are the smallest numbers possible for the rational number.
To reduce a fraction to its lowest terms, the greatest common divisor (GCD) of the numerator and denominator must be found. This is the largest number that both parts of the fraction may be divided by, whilst retaining two integers. The ReduceToLowestTerms method calls a further method to determine the GCD and divides the numerator and denominator by this value.
Add the ReduceToLowestTerms method to the structure:
private void ReduceToLowestTerms()
{
int greatestCommonDivisor = RationalNumber.GetGCD(_numerator, _denominator);
_numerator /= greatestCommonDivisor;
_denominator /= greatestCommonDivisor;
}
31 May 2008