Why does (int)55 == 54 in C++?

前端 未结 8 1289
旧巷少年郎
旧巷少年郎 2020-12-31 01:32

So I\'m learning C++. I\'ve got my \"C++ Programming Language\" and \"Effective C++\" out and I\'m running through Project Euler. Problem 1...dunzo. Problem 2...not so mu

8条回答
  •  被撕碎了的回忆
    2020-12-31 01:50

    All the above suggestions not to use floating point values for integer mathematics are worth noting!

    If you want integer "rounding" for positive floating point values so that values with a fractional component below 0.5 round to the next lowest integer, and values with a fractional component of 0.5 or greater round to the next higher integer, e.g.

    0.0 = 0
    0.1 = 0
    0.5 = 1
    0.9 = 1
    1.0 = 1
    1.1 = 1
    ...etc...    
    

    Add 0.5 to the value you are casting.

    double f0 = 0.0;
    double f1 = 0.1;
    double f2 = 0.5;
    double f3 = 0.9;
    
    int i0 = ( int )( f0 + 0.5 );  // i0 = 0
    int i1 = ( int )( f1 + 0.5 );  // i1 = 0
    int i2 = ( int )( f2 + 0.5 );  // i2 = 1
    int i3 = ( int )( f3 + 0.5 );  // i3 = 1
    

提交回复
热议问题