C++ 科学计数法和精度问题

C++ 科学计数法和精度问题
(来源于C++入门经典第三版)

// Program 2.8 Experimenting with floating point output
#include  // fixed scientific
#include  // setprecision()

using std::setprecision;
using std::fixed;
using std::scientific;
using std::cout;
using std::endl;

int main() {
  float value1 = 0.1f;
  float value2 = 2.1f;
  value1 -= 0.09f;                        // Should be 0.01
  value2 -= 2.09f;                        // Should be 0.01

  cout << value1 - value2 << endl; 
  
  cout << setprecision(14) << fixed;      // Change to fixed notation
  cout << value1 - value2 << endl;        // Should output zero

  cout << setprecision(2) << scientific;  // Set scientific notation
  cout << value1 - value2 << endl;        // Should output zero

  return 0;
}

输出

7.45058e-009
0.00000000745058
7.45e-009

你可能感兴趣的:(C/C++基础)