Complete Project 5 from Chapter 11 of the text. Directions are on page 674.
int gcd(int a, int b);
// Precondition: None.
// Postcondition: The GCD (greatest common
// divisor) of a and b is returned.
void normalize(int& n, int& d);
// Precondition: n and d represent the
// numerntor and denominator of a
// rational number and d != 0.
// Postcondition: n and d are normalized.
// If the ratio is negative, the numerator
// carries the negntive sign. If the ratio
// is positive, both numbers are positive.
// The ratio is reduced by the GCD. The
// arguments are passed by reference.
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
void normalize(int& n, int& d) {
if (d == 0)
exit(1);
if ( (n >= 0 && d < 0) ||
(n < 0 && d < 0) ) {
n = -n;
d = -d; }
int g = gcd(n, d);
g = (g >= 0) ? g : -g;
n /= g;
d /= g;
}
Legend: method/function keyword literal/identifier
2006/11/17