avoid rounding error (floating specifically) c++

前端 未结 6 1545
耶瑟儿~
耶瑟儿~ 2021-02-04 12:54

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/ I have been about this lately to review C++.

In general computing class professors tend not to cover thes

6条回答
  •  情书的邮戳
    2021-02-04 13:34

    In other words, to minimize rounding errors, it can be helpful to keep numbers in decimal fixed-point (and actually work with integers).

    #include 
    #include 
    
    int main() {
    
      using namespace std;
    
      cout << setprecision(17);
    
      double v1=1, v1D=10; 
      cout << v1/v1D << endl;  // 0.10000000000000001
    
    
      double v2=3, v2D=1000;  //0.0030000000000000001
      cout << v2/v2D << endl;
    
      // v1/v1D + v2/v2D = (v1*v2D+v2*v1D)/(v1D*v2D)
    
      cout << (v1*v2D+v2*v1D)/(v1D*v2D) << endl; // 0.10299999999999999
    
    }
    

提交回复
热议问题