|
-
Dec 20th, 2000, 09:26 PM
#1
Thread Starter
Fanatic Member
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?
-
Dec 21st, 2000, 05:55 AM
#2
Frenzied Member
You could just add 0.5 and round down.
Harry.
"From one thing, know ten thousand things."
-
Dec 21st, 2000, 05:18 PM
#3
Monday Morning Lunatic
Code:
long round(float value) {
// Round to nearest integer
if((long)value == (long)(value + 0.5f))
return (long)value;
else
return (long)(value+1);
}
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Dec 21st, 2000, 06:47 PM
#4
Thread Starter
Fanatic Member
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?
-
Dec 21st, 2000, 06:54 PM
#5
Monday Morning Lunatic
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
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Dec 21st, 2000, 07:11 PM
#6
Thread Starter
Fanatic Member
That should go to 5 though, not 4.
-
Dec 21st, 2000, 07:13 PM
#7
Monday Morning Lunatic
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.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Dec 22nd, 2000, 02:06 PM
#8
Frenzied Member
Looks like you're confusing each other Wynd, use something like this:
Code:
long RoundToNearest(float fNum)
{ return( (long)(fNum + 0.5f) );
}
Then use it like:
Code:
lRoundedNum = RoundToNearest(fNum)
Harry.
"From one thing, know ten thousand things."
-
Dec 22nd, 2000, 07:30 PM
#9
Thread Starter
Fanatic Member
Yeah, the "round to nearest integer" was what I was trying to do, but I couldn't figure out how to say it. Thanks!
-
Dec 22nd, 2000, 07:42 PM
#10
Monday Morning Lunatic
If you really need the speed you can do it the nasty macro way:
Code:
#define RoundToNearest(x) ((long)(x + 0.5f))
That's fairly safe, though, since x is only used once.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|