Chinaunix首页 | 论坛 | 博客
  • 博客访问: 42859
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 145
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-19 10:39
文章分类

全部博文(13)

文章存档

2016年(3)

2015年(5)

2014年(5)

我的朋友

分类: C/C++

2015-02-12 21:35:38


点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <cfloat>
  3. #include <cmath>

  4. using namespace std;

  5. int main(int argc, char* argv[])
  6. {
  7.     float a = 102.1f;
  8.     float b = 0.2f;
  9.     float c = a + b;    // 102.3f
  10.     if( c == 102.3f ) {
  11.         cout << a << " + " << b << " = " << 102.3f << endl;
  12.     } else {
  13.         cout << a << " + " << b << " != " << 102.3f << endl;    // Do Else
  14.     }

  15.     float d = a - 100.0f;
  16.     if( d == 2.1f ) {
  17.         cout << a << " - 100 " << " = " << 2.1f << endl;
  18.     } else {
  19.         cout << a << " - 100 " << " != " << 2.1f << endl;    // Do Else
  20.     }

  21.     float e = 0.3f;
  22.     if( (e * 3) == 0.9f ) {
  23.         cout << e << " * 3 " << " = " << 0.9f << endl;
  24.     } else {
  25.         cout << e << " * 3 " << " != " << 0.9f << endl;    // Do Else
  26.     }

  27.     //
  28.     // The Right judgement expression
  29.     // abs(a - xxx) <= 1.0e-5 // here 1.0e-5 is an epsilon, can't be other float number instead.
  30.     //
  31.     cout << "c = " << c << endl;
  32.     float epsilon1 = 1.0e-5;
  33.     float epsilon2 = 1.0e-6;
  34.     float standard_EPSILON = FLT_EPSILON;    // #include <cfloat>
  35.     cout << "FLT_EPSILON = " << standard_EPSILON << endl;

  36.     cout << "Now use epsilon1 = " << epsilon1 << endl;
  37.     if( abs(c - 102.3f) <= epsilon1 ) {
  38.         cout << "In if <= epsilon1 c == 102.3" << endl;    // In if epsilon1 is matched
  39.     } else {
  40.         cout << "In else > epsilon1 c != 102.3" << endl;
  41.     }


  42.     cout << "Now use epsilon2 = " << epsilon2 << endl;
  43.     if( abs(c - 102.3f) <= epsilon2 ) {
  44.         cout << "In if <= epsilon2 c == 102.3" << endl;
  45.     } else {
  46.         cout << "In else > epsilon2 c != 102.3" << endl;    // In else epsilon2 is not matched
  47.     }

  48.     return 0;
  49. }



阅读(1093) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~