example15.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <iostream>
  2. #include <limits>
  3. #include <boost/rational.hpp>
  4. #include <boost/safe_numerics/safe_integer.hpp>
  5. int main(int, const char *[]){
  6. // simple demo of rational library
  7. const boost::rational<int> r {1, 2};
  8. std::cout << "r = " << r << std::endl;
  9. const boost::rational<int> q {-2, 4};
  10. std::cout << "q = " << q << std::endl;
  11. // display the product
  12. std::cout << "r * q = " << r * q << std::endl;
  13. // problem: rational doesn't handle integer overflow well
  14. const boost::rational<int> c {1, INT_MAX};
  15. std::cout << "c = " << c << std::endl;
  16. const boost::rational<int> d {1, 2};
  17. std::cout << "d = " << d << std::endl;
  18. // display the product - wrong answer
  19. std::cout << "c * d = " << c * d << std::endl;
  20. // solution: use safe integer in rational definition
  21. using safe_rational = boost::rational<
  22. boost::safe_numerics::safe<int>
  23. >;
  24. // use rationals created with safe_t
  25. const safe_rational sc {1, INT_MAX};
  26. std::cout << "c = " << sc << std::endl;
  27. const safe_rational sd {1, 2};
  28. std::cout << "d = " << sd << std::endl;
  29. std::cout << "c * d = ";
  30. try {
  31. // multiply them. This will overflow
  32. std::cout << sc * sd << std::endl;
  33. }
  34. catch (std::exception const& e) {
  35. // catch exception due to multiplication overflow
  36. std::cout << e.what() << std::endl;
  37. }
  38. return 0;
  39. }