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);} }
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.
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 is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
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); }
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
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);
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}