fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. struct tabber
  5. {
  6. static unsigned width;
  7. static unsigned increment;
  8.  
  9. unsigned increments = 0;
  10.  
  11. tabber() : increments(0) { }
  12. tabber(const tabber&) = delete;
  13.  
  14. tabber(unsigned count) : increments(count) { width += increment * increments; }
  15. ~tabber() { width -= increments * increment; }
  16.  
  17. tabber& operator=(const tabber&) = delete;
  18.  
  19. tabber& inc() { ++increments; width += increment; return *this; }
  20. tabber& dec() { if (increments) { --increments; width -= increment; } return *this; }
  21. };
  22.  
  23. unsigned tabber::width = 0;
  24. unsigned tabber::increment = 3;
  25.  
  26. std::ostream& operator<<(std::ostream& os, const tabber& tab)
  27. {
  28. if ( tabber::width )
  29. os << std::setw(tabber::width) << ' ';
  30.  
  31. return os;
  32. }
  33.  
  34.  
  35. float return_value(tabber& t, float value)
  36. {
  37. std::cout << t.dec() << value << '\n';
  38. return value;
  39. }
  40.  
  41. float pow(int base, int power)
  42. {
  43. tabber t;
  44. std::cout << t << "pow(" << base << ", " << power << ")\n";
  45. t.inc();
  46.  
  47. if (power == 0)
  48. return return_value(t, 1.0);
  49.  
  50. if (power == 1)
  51. return return_value(t, base);
  52.  
  53. if (base < 0)
  54. {
  55. std::cout << t << "base is negative - recalling with positive base.\n";
  56. return return_value(t, pow(-base, power));
  57. }
  58.  
  59. if (power < 0)
  60. {
  61. std::cout << t << "power is negative - recalling with positive power.\n";
  62. float value = 1.0 / pow(base, -power);
  63.  
  64. std::cout << t << "Since power was negative, dividing 1.0 by return value.\n";
  65. return return_value(t, value);
  66. }
  67.  
  68. return return_value(t, base * pow(base, power - 1));
  69. }
  70.  
  71. int main()
  72. {
  73. int base = 2;
  74. int power = -3;
  75.  
  76. pow(base, power);
  77. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
pow(2, -3)
   power is negative - recalling with positive power.
   pow(2, 3)
      pow(2, 2)
         pow(2, 1)
         2
      4
   8
   Since power was negative, dividing 1.0 by return value.
0.125