• Source
    1.  
    2. // FLOAT 大小比較 EPS
    3.  
    4. #include <cstdio>
    5. #include <cmath>
    6. #include <iostream>
    7. using namespace std;
    8.  
    9. #define EPS (1e-9)
    10.  
    11. #define FLOAT FLOAT_
    12.  
    13. template <class T>
    14. struct FLOAT
    15. {
    16. T value;
    17. FLOAT(T _) : value(_) { }
    18. FLOAT operator +() const { return *this; }
    19. FLOAT operator -() const { return -value; }
    20. FLOAT operator +(FLOAT _) const { return value + _.value; }
    21. FLOAT operator -(FLOAT _) const { return value - _.value; }
    22. FLOAT operator *(FLOAT _) const { return value * _.value; }
    23. FLOAT operator /(FLOAT _) const { return value / _.value; }
    24. FLOAT & operator +=(FLOAT _) { value += _.value; return *this; }
    25. FLOAT & operator -=(FLOAT _) { value -= _.value; return *this; }
    26. FLOAT & operator *=(FLOAT _) { value *= _.value; return *this; }
    27. FLOAT & operator /=(FLOAT _) { value /= _.value; return *this; }
    28. bool operator ==(FLOAT _) const { return abs(value - _.value) < EPS; }
    29. bool operator !=(FLOAT _) const { return abs(value - _.value) > EPS; }
    30. bool operator < (FLOAT _) const { return value - _.value < -EPS; }
    31. bool operator <=(FLOAT _) const { return value - _.value < EPS; }
    32. bool operator > (FLOAT _) const { return value - _.value > EPS; }
    33. bool operator >=(FLOAT _) const { return value - _.value > -EPS; }
    34. };
    35. template <class T> inline ostream& operator << (ostream &out, FLOAT<T> _) { out << _.value; return out; }
    36. template <class T> inline istream& operator >> (istream &in, FLOAT<T> &_) { in >> _.value; return in; }
    37.  
    38. #define double FLOAT<double>
    39. #define float FLOAT<float>
    40.  
    41. int main()
    42. {
    43. double d = 1e-11f;
    44. cout << d << endl;
    45. cout << "(d == d + d) = " << (d == d + d) << endl; // true.
    46. cout << "(d == 1e-10f) = " << (d == 1e-10f) << endl; // true.
    47.  
    48. d *= 1e3;
    49. cout << "(d == d + d) = " << (d == d + d) << endl; // false.
    50.  
    51. double e = EPS;
    52. e += d + 1e-11f;
    53. e *= 10000;
    54. cout << "cout e = " << e << endl;
    55. printf("printf e = %0.12f\n", e);
    56.  
    57. return 0;
    58. }
    59.