void rational::normalize() { // normalize rational by (a) moving sign to numerator : // b) making sure numerator and denominator have no common divisors int sign = 1; // sign is 1 if non-negative, -1 if negative if (top < 0) { sign = -1; top = - top; } if (bottom < 0) { sign = - sign; bottom = - bottom; } // make sure we are not dividing by zero if (bottom == 0) throw range_error("fraction with zero numerator"); // find greatest common divisor int d = gcd(top, bottom); // move sign to top and divide by gcd top = sign * (top / d); bottom = bottom / d;

Previous slide Next slide Back to first slide View graphic version