round() for float in C++

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

    If you ultimately want to convert the double output of your round() function to an int, then the accepted solutions of this question will look something like:

    int roundint(double r) {
      return (int)((r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5));
    }
    

    This clocks in at around 8.88 ns on my machine when passed in uniformly random values.

    The below is functionally equivalent, as far as I can tell, but clocks in at 2.48 ns on my machine, for a significant performance advantage:

    int roundint (double r) {
      int tmp = static_cast (r);
      tmp += (r-tmp>=.5) - (r-tmp<=-.5);
      return tmp;
    }
    

    Among the reasons for the better performance is the skipped branching.

提交回复
热议问题