-5

Which is the shortest form of this function(without changing the name of this)?

int NearestInteger(float N) 
{
    return round(N);
}
Shehary
  • 9,926
  • 10
  • 42
  • 71
Vasiu Alexandru
  • 103
  • 3
  • 16

2 Answers2

2

You can use std::round function if you have C++11.

Otherwise, you may need to use one of them depends on your requirement std::floor or std::ceil

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Steephen
  • 14,645
  • 7
  • 40
  • 47
1

If you don't have C++11, you can do this:

int NearestInteger(float N) {
    return int(floor(N + 0.5f));
}

However, it may work incorrectly for large floats. First of all, if your number does not fit int, any trash can be returned. Second, it may return wrong results for numbers larger than 2^24, because not each integer is exactly representable in single precision float number.

Community
  • 1
  • 1
stgatilov
  • 5,333
  • 31
  • 54