round to the nearest integer

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
LittleJohn
Learning poster
Posts: 83
Joined: Wed Feb 27, 2002 2:00 am
Location: Taiwan

Post by LittleJohn » 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!! ^^

pochmann
New poster
Posts: 28
Joined: Sat Jan 26, 2002 2:00 am
Contact:

Post by pochmann » Thu Feb 28, 2002 5:35 am

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

Post by LittleJohn » 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;
}

Stefan Pochmann
A great helper
Posts: 284
Joined: Thu Feb 28, 2002 2:00 am
Location: Germany
Contact:

Post by Stefan Pochmann » 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

shahriar_manzoor
System administrator & Problemsetter
Posts: 399
Joined: Sat Jan 12, 2002 2:00 am

Post by shahriar_manzoor » Thu Feb 28, 2002 4:32 pm

Do you know that
round(x) = floor(x+0.5);
I think this is the best solution.

Post Reply

Return to “C”