Hi everyone,
I was just wondering - is this a valid way to round to the nearest integer in C++?
Thanks a lot.Code:double round(double x)
{
if(x<0){return ceil(x-0.5);}
else if(x>0){return floor(x+0.5);}
else {return(x=0);}
}
Printable View
Hi everyone,
I was just wondering - is this a valid way to round to the nearest integer in C++?
Thanks a lot.Code:double round(double x)
{
if(x<0){return ceil(x-0.5);}
else if(x>0){return floor(x+0.5);}
else {return(x=0);}
}
Test your function and see if the answer is right.:rolleyes:
I tried it and it worked for the numbers I put in, but I didn't know if there was anything I had missed. I guess it's ok!
Remember to test the infinities and NaN. Cause right now, NaN will give the wrong answer.
It's valid, but overkill.
floor rounds towards minus infinity and ceil rounds towards positive infinity. So they both have the same behaviour either side of zero. This means that you don't need to use both. There's also no reason to have a special case for zero because the floor of zero plus 0.5 is still zero. So all you need is:
Code:double round(double x)
{
return floor(x+0.5);
}
Thanks for the help - I found iMalc's suggestion in other places, but people seemed to be saying that it didn't work for negatives. On second thought, it does, doesn't it?
Thanks!
It depends whether you want the result to be a double or an integer. It is common to round by casting to int like this:
The above does NOT do the right thing if x is negative, because integer truncation goes toward zero, it's not like floor()Code:double x = ...;
int rounded = (int)(x + 0.5);