How to round to the nearest odd? C++

I want to make any decimal point in even to go to odd and any decimal point in odd stay as odd in C++.

2 to 2.9 becomes 3.
1 to 1.9 becomes 1.

I would like to do something like;
cout << "The nearest odd number is " << (insert odd formula) << endl;
Haven't checked, but maybe this would work:
1
2
3
4
int nearestOdd( float x )
{
  return 2 * ( (int)(x / 2.0f) ) + 1;
}
Last edited on
Using <cmath>...
1
2
3
4
5
6
7
8
9
//Pseudocode
If(floor(x) / 2 != 0) //If the number is an odd decimal. 
{
answer = floor(x); //The answer is that number. 
}
else //Otherwise
{
answer = ceil(x); //Closest odd number is going to be above. 
}


You might want to add code to check for even integers, as these are equidistant, but will be thrown by this program into the else{} case.

floor(n) - Rounds down a number.
ceil(n) - Round up a number.
Last edited on
Topic archived. No new replies allowed.