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?
Printable View
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?
You could just add 0.5 and round down.
Code:long round(float value) {
// Round to nearest integer
if((long)value == (long)(value + 0.5f))
return (long)value;
else
return (long)(value+1);
}
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?
To round down, simply cast to an integer type - rounding down is the same as truncating the fractional portion:
Code:float fNum = 4.6;
int iNum = (int)fNum; // =4
That should go to 5 though, not 4.
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.
Looks like you're confusing each other ;) Wynd, use something like this:
Then use it like:Code:long RoundToNearest(float fNum)
{ return( (long)(fNum + 0.5f) );
}
Code:lRoundedNum = RoundToNearest(fNum)
Yeah, the "round to nearest integer" was what I was trying to do, but I couldn't figure out how to say it. Thanks!
If you really need the speed you can do it the nasty macro way:
That's fairly safe, though, since x is only used once.Code:#define RoundToNearest(x) ((long)(x + 0.5f))