Case Study - Fractions

5/31/00


Click here to start


Table of Contents

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

Operators

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 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;

Member Function Operators

Conversion Operations

Conversion Operations

Conversion Operations

Input and Output Streams

Input and Output Streams

Stream Input

istream & operator >> (istream & in, rational & r) { // read a rational number from an input stream int t, b; // read the top in >> t; // if there is a slash, read the next number char c; in >> c; if (c == '/') in >> b; // read bottom part else { in.putback(c); b = 1; } // do the assignment rational newValue(t, b); r = newValue; // return the stream return in;

Author: Seung Sean Yoo

Email: budd@cs.orst.edu

Home Page: http://www.cs.orst.edu/~budd