round() for float in C++

后端 未结 22 1168
时光取名叫无心
时光取名叫无心 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:30

    There's no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of round-half-up:

    double round(double d)
    {
      return floor(d + 0.5);
    }
    

    The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.

提交回复
热议问题