modf returns 1 as the fractional:

前端 未结 2 1783
别跟我提以往
别跟我提以往 2021-01-24 05:17

I have this static method, it receives a double and \"cuts\" its fractional tail leaving two digits after the dot. works almost all the time. I have noticed that when i

2条回答
  •  情话喂你
    2021-01-24 05:56

    Remember floating point number cannot represent decimal numbers exactly. 2.3 * 100 actually gives 229.99999999999997. Thus modf returns 229 and 0.9999999999999716.

    However, cout's format will only display floating point numbers to 6 decimal places by default. So the 0.9999999999999716 is shown as 1.


    You could use (roughly) the upper error limit that a value represents in floating point to avoid the 2.3 error:

    #include 
    #include 
    static double dRound(double d) {
       double inf = copysign(std::numeric_limits::infinity(), d);
       double theNumberAfter = nextafter(d, inf);
       double epsilon = theNumberAfter - d;
    
       int factor = 100;
       d *= factor;
       epsilon *= factor/2;
       d += epsilon;
    
       double returnVal;
       modf(number, &returnVal);
       return returnVal / factor;
    }
    

    Result: http://www.ideone.com/ywmua

提交回复
热议问题