#ifndef __FRACTION_H__ #define __FRACTION_H__ #include // The line below that reads "// #define BIG" is a cute bit of magic. // If it's uncommented (and BIG is defined), then the definition of the // type myInt is taken as the class Integer, included from Integer.h. // This class is GNU's implementation of a BigInt class, an arbitrary // precision integer. This class supports arbitarily large integers, // which means that overflow is impossible in the Fraction class! It // also means that your fractions can be as precise as you want. // // Unfortunately, the Integer class is only available on UNIX systems // using GNU g++. If you're in the IPL, or in general using MSVC, you // don't have access to this class. // // If you leave BIG undefined, you make the myInt type be my SafeInt class, // which is a kind of integer that automatically detects overflow. See // safeops.h for more details. // #define BIG #ifdef BIG #include typedef Integer myInt; inline bool good( myInt& ) { return true; } #else #include "safeops.h" typedef SafeInt myInt; #endif class Fraction { public: // initialize the fraction to NaN Fraction(); // initialize the fraction to i Fraction(myInt i); // initialize the fraction to numerator/denominator Fraction(myInt numerator, myInt denominator); Fraction operator+(Fraction rhs); Fraction operator-(Fraction rhs); Fraction operator*(Fraction rhs); Fraction operator/(Fraction rhs); // unary - operator Fraction operator-(); bool operator==(Fraction rhs); // return true iff the fraction is Not a Number bool NaN(); // return true iff the fraction is positive infinity bool Inf(); // return true iff the fraction is negative infinity bool NegInf(); // print the fraction as / to the stream os // the fraction must be in lowest terms, and the denominator must not // be negative (i.e. negative fractions must have the '-' in the numerator void print(ostream& os); // fill the buffer buf with the decimal value of the fraction to as // high a precision as possible without exceeding length len-1 // return false if len did not allow sufficient room to represent // NaN, Inf, or -Inf, or the number prior to the decimal point bool expand(char buf[], int len); // return the double best approximating the value of the fraction double toDouble(); private: void init( myInt numerator, myInt denominator ); myInt num; myInt den; }; ostream& operator<<(ostream& os, Fraction f); #endif