## round to the nearest integer

Write here if you have problems with your C source code

Moderator: Board moderators

LittleJohn
Learning poster
Posts: 83
Joined: Wed Feb 27, 2002 2:00 am
Location: Taiwan
hi, all:
I include <math.h> and use the "rint" function. Its return type is double. My code is just like "int = (int)rint(double)." It can work correctly on my machine. But I don't know whether the online judge system can work or not. I have an experience that in a Wrong Answer program I use "int = (int)rint(double)", but when I write the "rint" function by myself and I got Accepted. If anyone got the same trouble with me? Or can anybody share your experience to get the integer that is nearest to a double type variable. I hate the floating point error ><... Thanks Anyway!! ^^

pochmann
New poster
Posts: 28
Joined: Sat Jan 26, 2002 2:00 am
Contact:
I think it always worked fine for me. Can we see your self-written function?

Stefan

LittleJohn
Learning poster
Posts: 83
Joined: Wed Feb 27, 2002 2:00 am
Location: Taiwan
int round(double d)
{
double f, c;
f = floor(d);
c = ceil(d);
if (c - d > d - f)
return (int)f;
else
return (int)c;
}

Stefan Pochmann
A great helper
Posts: 284
Joined: Thu Feb 28, 2002 2:00 am
Location: Germany
Contact:
Hmm, looks good. I can't really imagine why this should differ to rint(...). Maybe you had a value close to x.5 and your subtractions cause rounding errors that result in a different value than rint(), which will probably not do any computation.

But with this, my advice can only be: "Good *luck* next time". A value close to x.5 will *always* be risky.

What you can sometimes do is check back whether the value is correct. For example, say you've calculated y=rint(sqrt(x)). Then check if y*y==x and if not, try y-1 and y+1.

Stefan

shahriar_manzoor