Rational.h
1 //-*-C++-*-
2 /***************************************************************************
3  *
4  * Copyright (C) 2018 by Willem van Straten
5  * Licensed under the Academic Free License version 2.1
6  *
7  ***************************************************************************/
8 
9 #ifndef __Rational_h
10 #define __Rational_h
11 
12 #include <iostream>
13 
15 class Rational
16 {
17  friend std::istream& operator >> (std::istream& in, Rational& r);
18  friend std::ostream& operator << (std::ostream& out, const Rational& r);
19 
20 public:
21 
22  explicit Rational(int numerator = 0, unsigned denominator = 1);
23 
24  const Rational& operator = (const Rational&);
25  bool operator == (const Rational&) const;
26  bool operator != (const Rational&) const;
27 
28  const Rational& operator = (int num);
29  bool operator == (int num) const;
30  bool operator != (int num) const;
31 
32  int operator * (int num) const;
33 
34  double doubleValue( ) const;
35 
36  /* divides argument by self and throws an exception if the
37  result is not an integer */
38  int normalize (int) const ;
39 
40  // double normalize (double) const;
41 
42  int get_numerator () const {
43  return numerator;
44  }
45 
46  unsigned get_denominator () const {
47  return denominator;
48  }
49 
50 private:
51  int numerator;
52  unsigned denominator;
53  void reduce( );
54 
55 };
56 
57 template<typename T>
58 T operator * (T x, const Rational& q)
59 {
60  return (x * q.get_numerator()) / q.get_denominator();
61 }
62 
63 template<typename T>
64 T operator / (T x, const Rational& q)
65 {
66  return (x * q.get_denominator()) / q.get_numerator();
67 }
68 
69 template<typename T>
70 bool operator > (const Rational& q, T x)
71 {
72  return q.get_numerator() > (x * q.get_denominator());
73 }
74 
75 template<typename T>
76 bool operator < (const Rational& q, T x)
77 {
78  return q.get_numerator() < (x * q.get_denominator());
79 }
80 
81 #endif // !defined(__Rational_h)
Represents a rational number.
Definition: Rational.h:15

Generated using doxygen 1.8.17