You're using flotating-point double-precision numbers, those cannot represent all the real (not even all the rational) numbers exactly. You might have better luck with Boost Rational Number Library (header-only, no need to build separately):
http://www.boost.org/doc/libs/release/libs/rational/
Example program:
http://www.boost.org/doc/libs/1_37_0...al_example.cpp
The above, sample run:
http://www.ideone.com/cVA7X