round() for float in C++

后端 未结 22 1173
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find

22条回答
  •  清酒与你
    2020-11-22 03:16

    There are 2 problems we are looking at:

    1. rounding conversions
    2. type conversion.

    Rounding conversions mean rounding ± float/double to nearest floor/ceil float/double. May be your problem ends here. But if you are expected to return Int/Long, you need to perform type conversion, and thus "Overflow" problem might hit your solution. SO, do a check for error in your function

    long round(double x) {
       assert(x >= LONG_MIN-0.5);
       assert(x <= LONG_MAX+0.5);
       if (x >= 0)
          return (long) (x+0.5);
       return (long) (x-0.5);
    }
    
    #define round(x) ((x) < LONG_MIN-0.5 || (x) > LONG_MAX+0.5 ?\
          error() : ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
    

    from : http://www.cs.tut.fi/~jkorpela/round.html

提交回复
热议问题