test_rational.cpp

00001 #include <cmath>
00002 #include <sstream>
00003 
00004 #include "rational.hpp"
00005 #include "test.hpp"
00006 
00007 void test_rational()
00008 {
00009   rational<int> zero;
00010   rational<int> one(1);
00011   rational<int> half(10, 20);
00012   rational<int> third(-10, -30);
00013   rational<int> minus_one(-10, 10);
00014 
00015   TEST(minus_one == -one);
00016   TEST(one - one == zero);
00017   TEST(zero == 0);
00018   TEST(0 == zero);
00019   TEST(zero < one);
00020   TEST(zero <= one);
00021   TEST(half >= third);
00022   TEST(half > third);
00023   TEST(half != third);
00024 
00025   TEST(-half < 0);
00026   TEST(-half <= 0);
00027   TEST(half > 0);
00028   TEST(half >= 0);
00029   TEST(0 < half);
00030   TEST(0 <= half);
00031   TEST(0 != half);
00032   TEST(half != 0);
00033 
00034   TEST(half * 2 == one);
00035   TEST(2 * half == one)
00036   TEST(third * 3 == one);
00037   TEST(3 / one == 3);
00038   TEST(one / 3 == third);
00039   TEST(half + half == one);
00040   TEST(one - half == half);
00041   TEST((half + 1) * 2 == 1 / third);
00042 
00043   std::stringstream stream;
00044   TEST(stream << third);
00045   TEST(stream.str() == "1/3");
00046   rational<int> check;
00047   TEST(stream >> check);
00048   TEST(check == third);
00049 
00050   rational<long> long_pi(1414847550L, 450359962L);
00051   rational<short> short_pi(long_pi);
00052   // The following test works only if short has less precision and range than long.
00053   TEST(long_pi != short_pi);
00054   // The following test works if long has >= 32 bits and short has 16 bits.
00055   TEST(short_pi == rational<short>(3598, 1145));
00056   rational<short> assign_pi;
00057   assign_pi = long_pi;
00058   TEST(short_pi == assign_pi);
00059 
00060   TEST(std::abs(third.as<double>() - 0.333333333) < 0.000000001);
00061 
00062   TEST(++zero == one);
00063   TEST(zero == one);
00064   TEST(zero++ == one);
00065   TEST(zero == 2);
00066   TEST(--zero == one);
00067   TEST(zero == one);
00068   TEST(zero-- == one);
00069   TEST(zero == 0);
00070 
00071   bool okay(false);
00072   try {
00073     // Check that a zero denominator really throws an exception.
00074     rational<int> impossible(1, 0);
00075   } catch(rational<int>::zero_denominator const& ex) {
00076     okay = true;
00077   }
00078   TEST(okay);
00079 }

Generated on Sun Nov 30 09:53:23 2008 for Exploring C++ - Final Forms of Key Examples by  doxygen 1.5.3