# In Dev-C++, how can I make a rounding to nearest integer?

Discussion in 'C++' started by Mr. Ken, May 25, 2006.

1. ### Mr. KenGuest

Here are the funny results I got from Dev-C++, what I need is rounding to
nearest integer.
How can I do that in Dev-C++?

a = -1 -1 -1 -1 1 1 2 2 2 1
b = round(a)
-0.729627 -0.9540721 -0.2123411 -0.078923 0.321015 0.9876552 1.123422
1.632136 1.234538 0.765442
c = int(a)
0 0 0 0 0 0 1 1 1 0

My required data.
c =
-1 -1 0 0 0 1 1 2 1 1

Thank you.

Mr. Ken, May 25, 2006

2. ### Jim LangstonGuest

"Mr. Ken" <Mr. Ken@asdf> wrote in message
news:44756dac\$...
> Here are the funny results I got from Dev-C++, what I need is rounding to
> nearest integer.
> How can I do that in Dev-C++?
>
>
> a = -1 -1 -1 -1 1 1 2 2 2 1
> b = round(a)
> -0.729627 -0.9540721 -0.2123411 -0.078923 0.321015 0.9876552 1.123422
> 1.632136 1.234538 0.765442
> c = int(a)
> 0 0 0 0 0 0 1 1 1 0
>
> My required data.
> c =
> -1 -1 0 0 0 1 1 2 1 1

I think you are just trying to round
-0.729627 -0.9540721 -0.2123411 -0.078923 0.321015 0.9876552 1.123422
1.632136 1.234538 0.765442

to the nearest int instead of truncating them, correct?

c = static_cast<int>( a < 0 ? a - 0.5 : a + 0.5 );

static_cast<int>() is the c++ way to do (int) casting.

the
a < 0 : a - 0.5 : a + 0.5
is the ternary statement. it's similar (but not the same) as
if ( a < 0 )
return a - 0.5;
else
return a + 0.5;

Jim Langston, May 25, 2006

3. ### TomásGuest

RoundOff

Jim Langston posted:

> Simply add (or subtract) .5
>
> c = static_cast<int>( a < 0 ? a - 0.5 : a + 0.5 );
>
> static_cast<int>() is the c++ way to do (int) casting.
>
> the
> a < 0 : a - 0.5 : a + 0.5
> is the ternary statement. it's similar (but not the same) as
> if ( a < 0 )
> return a - 0.5;
> else
> return a + 0.5;

template<class Integral,class Floating>
inline Integral RoundOff(Floating const d)
{
return static_cast<Integral>(
(d < Floating(0)) ? (d - Floating(.5)) : (d + Floating(.5))
);

/* static_cast only used to supress compiler truncation warning */
}

int main()
{
float b = 34.23;

long k = RoundOff<long>(b);
}

-Tomás

Tomás, May 25, 2006