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

M

Mr. Ken

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.
 
J

Jim Langston

Mr. Ken said:
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?

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;
 
T

Tomás

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top