fork(1) download
  1. #include <cassert>
  2. #include <iostream>
  3. #include <cmath> // for std::abs
  4.  
  5. template<unsigned int DIM> class Test
  6. {
  7. private:
  8. double abs_error = 1e-6;
  9. double mData[DIM];
  10.  
  11. public:
  12. double& operator[](int index)
  13. {
  14. // To check that the input index is a valid one
  15. assert(index < DIM);
  16. assert(index > -1);
  17.  
  18. // Condition that checks for values between 0 and 1 inclusive
  19. if (mData[index] >= 0.0 && mData[index] <= 1.0)
  20. {
  21. return mData[index];
  22. }
  23.  
  24. // Values less than zero
  25. else if (std::abs(mData[index]) <= abs_error && mData[index] <= 0.0)
  26. {
  27. return mData[index] = 0;
  28. }
  29.  
  30. // Values more than one
  31. else if (mData[index] >= 1.0 && std::abs(mData[index] - 1.0) <= abs_error)
  32. {
  33. std::cout << "You used this condition." << std::endl;
  34. return mData[index] = 1;
  35. }
  36.  
  37. // For every other possible value
  38. else
  39. {
  40. assert(0);
  41. throw 42;
  42. }
  43.  
  44. return mData[index];
  45.  
  46. }
  47.  
  48. };
  49.  
  50.  
  51. int main()
  52. {
  53. Test<6> p;
  54. p[0] = 0.5;
  55. std::cout << "p[0]: " << p[0] << std::endl;
  56. p[1] = -1e-7;
  57. std::cout << "p[1]: " << p[1] << std::endl;
  58. // Comment the following two lines and check the test statement
  59. //p[2] = 1+1e-8;
  60. //std::cout << "p[2]: " << p[2] << std::endl;
  61.  
  62. // This code tests the same condition as in Test.h for
  63. // values more than one
  64. bool foo = 1+1e-8 >= 1.0 && std::abs(1+1e-8 - 1.0) <= 1e-6;
  65. std::cout << "foo (should return 1): " << foo << std::endl;
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
p[0]: 0.5
p[1]: 0
foo (should return 1): 1