Page 1 of 1
Posted: Wed Feb 27, 2002 6:37 pm
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!! ^^

Posted: Thu Feb 28, 2002 5:35 am
I think it always worked fine for me. Can we see your self-written function?

Stefan

Posted: Thu Feb 28, 2002 1:26 pm
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;
}

Posted: Thu Feb 28, 2002 1:47 pm
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

Posted: Thu Feb 28, 2002 4:32 pm
Do you know that
round(x) = floor(x+0.5);
I think this is the best solution.