fork(6) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <limits>
  4.  
  5. // Find the maximum number for double.
  6. // assuming:
  7. // (1) (a + b > b) if both a and b are not inf,
  8. // (2) not (a + b > b) => a or b is inf.
  9. // (3) not (a > a - 1) => a is max number of T or inf
  10.  
  11. using namespace std;
  12.  
  13. template <class T> void dump(T d) {
  14. for (int i = 0; i < sizeof(d); ++i) {
  15. cout << int(((unsigned char*)&d)[i]) << " ";
  16. }
  17. cout << endl;
  18. }
  19.  
  20. template <class T> bool is_usual_num(T n) {
  21. return (n + n > n) || (n > n - 1);
  22. }
  23.  
  24. template <class T> void find_max() {
  25. T d = T(1.0);
  26. while (1) {
  27. T n = d * 2.0;
  28. cout << "(!(n > d && is_usual_num(n))) " << bool(!(n > d && is_usual_num(n))) <<endl;
  29. if (!(n > d && is_usual_num(n))) {
  30. cout << "break" << endl;
  31. break;
  32. }
  33. d = n;
  34. }
  35.  
  36. T m = T(0);
  37. while (d >= 1.0) {
  38. T n = m + d;
  39. if (!(n > m && is_usual_num(n))) {
  40. break;
  41. }
  42. m = n;
  43. d = d / 2.0;
  44. }
  45.  
  46. std::cout << "calculated = " << +m << std::endl;
  47. std::cout << "numeric_limits = " << +numeric_limits<T>::max() << std::endl;
  48.  
  49. dump(m);
  50. dump(numeric_limits<T>::max());
  51. cout << endl;
  52. }
  53.  
  54. int main(int argc, const char * argv[]) {
  55.  
  56. cout << "char" << endl;
  57. find_max<char>();
  58.  
  59. //cout << "double" << endl;
  60. //find_max<double>();
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
char
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 0
(!(n > d && is_usual_num(n))) 1
(!(n > d && is_usual_num(n))) 0
break
calculated = 0
numeric_limits = 127
0 
127