Case Study - Fractions
Objectives
Example of Rational Numbers
Definition of Operations on Rational Numbers
// class rational// rational number data abstraction
Interface and Implementation
Constructors
Member Function
Operators
Unary Negation Operator
Comparison Operators
Increment and Decrement
Functions
Member Function Operators
void rational::normalize() { // normalize rational by (a) moving sign to numerator :// b) making sure numerator and denominator have no common divisorsint sign = 1; // sign is 1 if non-negative, -1 if negativeif (top < 0) { sign = -1; top = - top;}if (bottom < 0) { sign = - sign; bottom = - bottom;}// make sure we are not dividing by zeroif (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 gcdtop = sign * (top / d);bottom = bottom / d;
Conversion Operations
Input and Output Streams
Stream Input
istream & operator >> (istream & in, rational & r) { // read a rational number from an input streamint t, b;// read the topin >> t;// if there is a slash, read the next numberchar c;in >> c;if (c == '/') in >> b; // read bottom partelse { in.putback(c); b = 1;}// do the assignmentrational newValue(t, b);r = newValue;// return the streamreturn in;
Email: budd@cs.orst.edu
Home Page: http://www.cs.orst.edu/~budd