Click to See Complete Forum and Search --> : How do I check the value of a variable for rounding?
Wynd
Dec 20th, 2000, 08:26 PM
Right now, I have something like:
--
int x, y, z = 0
cin>>x;
x = ((y * 3 + z) / 4);
--
I am getting a decimal that I want rounded to a whole number. My question is, how can i see what the value is to know if i round up or down?
HarryW
Dec 21st, 2000, 04:55 AM
You could just add 0.5 and round down.
parksie
Dec 21st, 2000, 04:18 PM
long round(float value) {
// Round to nearest integer
if((long)value == (long)(value + 0.5f))
return (long)value;
else
return (long)(value+1);
}
Wynd
Dec 21st, 2000, 05:47 PM
Harry, how would i go about rounding down? Right now I have
x=x+0.5;
floor(x);
but it isn't working. Can you help at all?
parksie
Dec 21st, 2000, 05:54 PM
To round down, simply cast to an integer type - rounding down is the same as truncating the fractional portion:
float fNum = 4.6;
int iNum = (int)fNum; // =4
Wynd
Dec 21st, 2000, 06:11 PM
That should go to 5 though, not 4.
parksie
Dec 21st, 2000, 06:13 PM
Rounding 4.6 down gives 4.
Rounding 4.6 up gives 5.
Rounding 4.6 to the nearest integer gives 5.
Rounding 4.3 down gives 4.
Rounding 4.3 up gives 5.
Rounding 4.3 to the nearest integer gives 4.
HarryW
Dec 22nd, 2000, 01:06 PM
Looks like you're confusing each other ;) Wynd, use something like this:
long RoundToNearest(float fNum)
{ return( (long)(fNum + 0.5f) );
}
Then use it like:
lRoundedNum = RoundToNearest(fNum)
Wynd
Dec 22nd, 2000, 06:30 PM
Yeah, the "round to nearest integer" was what I was trying to do, but I couldn't figure out how to say it. Thanks!
parksie
Dec 22nd, 2000, 06:42 PM
If you really need the speed you can do it the nasty macro way:
#define RoundToNearest(x) ((long)(x + 0.5f))
That's fairly safe, though, since x is only used once.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.