Rounding a double to nearest odd int

Hello Everyone,

I hope you are all doing well.

I am having a bit of an issue and i have been going at it for quite some time and cannot figure it out.

I'm trying to input a double (ex: 1.2) and static_cast<int> it to the closest odd integer.

My current code which isn't working is:
cout << "Closest odd integer :" <<static_cast<int> (((x+1)/2)*2-1) << endl;

The assignment i'm doing requires the use of inputting a double and static casting it to an int.

any help or pointers would be greatly appreciated.

Thank You!
How about (in a function):

1) Cast the double to an int.
2) If it's odd, then you're done.
3) Otherwise, add one to the int.
http://www.cplusplus.com/doc/tutorial/typecasting/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
	double number;
	int newNumber;
	cout << "Enter Number: ";
	cin >> number;
	newNumber = static_cast<int>(number);
	if(newNumber%2==0)
	{
		newNumber+=1;
		cout << newNumber << endl;
	}
	else
	{
		cout << newNumber << endl;
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <limits>

int nearest_odd_integer( double v )
{
    if( v >= std::numeric_limits<int>::max() ) return std::numeric_limits<int>::max() ;
    else if( v <= std::numeric_limits<int>::min() ) return std::numeric_limits<int>::min() + 1 ;

    bool negative = false ;
    if( v < 0 ) { negative = true ; v = -v ; }

    int ival = v ; // truncation towards zero
    if( ival%2 == 0 ) ++ival ; // even, nearest odd integer is i+1

    return negative ? -ival : ival ;
}

int main()
{
    for( double d : { -1.0e+30, -2.9, -2.3, -2.0, -1.99, -0.6, -0.01, 0.0, +0.01, +0.7, +1.8, +2.0, +2.3, 1.0e+30,  } )
        std::cout << d << " => " << nearest_odd_integer(d) << '\n' ;
}

http://coliru.stacked-crooked.com/a/f2a0cb66c17c12d9
Topic archived. No new replies allowed.