error4.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //error4.cpp – using exception classes
  2. #include <iostream>
  3. #include <cmath> // or math.h, unix users may need -lm flag
  4. #include "exc_mean.h"
  5. // function prototypes
  6. double hmean(double a, double b);
  7. double gmean(double a, double b);
  8. int main()
  9. {
  10. using std::cout;
  11. using std::cin;
  12. using std::endl;
  13. double x, y, z;
  14. cout << "Enter two numbers: ";
  15. while (cin >> x >> y)
  16. {
  17. try { // start of try block
  18. z = hmean(x,y);
  19. cout << "Harmonic mean of " << x << " and " << y
  20. << " is " << z << endl;
  21. cout << "Geometric mean of " << x << " and " << y
  22. << " is " << gmean(x,y) << endl;
  23. cout << "Enter next set of numbers <q to quit>: ";
  24. }// end of try block
  25. catch (bad_hmean & bg) // start of catch block
  26. {
  27. bg.mesg();
  28. cout << "Try again.\n";
  29. continue;
  30. }
  31. catch (bad_gmean & hg)
  32. {
  33. cout << hg.mesg();
  34. cout << "Values used: " << hg.v1 << ", "
  35. << hg.v2 << endl;
  36. cout << "Sorry, you don't get to play any more.\n";
  37. break;
  38. } // end of catch block
  39. }
  40. cout << "Bye!\n";
  41. // cin.get();
  42. // cin.get();
  43. return 0;
  44. }
  45. double hmean(double a, double b)
  46. {
  47. if (a == -b)
  48. throw bad_hmean(a,b);
  49. return 2.0 * a * b / (a + b);
  50. }
  51. double gmean(double a, double b)
  52. {
  53. if (a < 0 || b < 0)
  54. throw bad_gmean(a,b);
  55. return std::sqrt(a * b);
  56. }