Hi,
I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number? Which one is prefered?
Thanks and regards!
Printable View
Hi,
I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number? Which one is prefered?
Thanks and regards!
They do different things. floor() rounds down, int() will truncate. The return types differ as well:
floor(-3.5) == -4 (double)
int(-3.5) == -3 (int)
>> I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number?
Conversion from float to int is (potentially) limited, so your best bet would be to stick with floating point specific functions.
EDIT:
>> floor(-3.5) == -4 (double)
Missed that one. :)
It depends whether you needs to put the value of the double into an integer or not. If you don't need to, then you'd just use floor.
If you do need to, I would consider using both to be more explicit.Code:doubld d2 = floor(d1);
By the way, int() as you queried about, is the constructor form of casting. The normal C++ way would be:Code:int i = int(floor(d));
and the C way isCode:int i = static_cast<int>(floor(d));
Code:int i = (int)floor(d);
I always thought that if the values are integer and positive the would both return the same value...but that is the only time that is the case...
If they were negative and integer then ceiling and truncation would give the sameCode:(int) floor (1.1) = 1
(int)1.1 = 1
could be wrong however...Code:(int) ceiling (-1.1) = -1
(int) -1.1 = -1
There's also trunc(). :-)
CH is correct- trunc is available in C99 standard:Quote:
I don't think so, but I haven't taken to 30+ minutes of booting windows to check. The man page seems to indicate that it should be available in windows:
trunc- Truncate to nearest integral value:
double trunc(double x);
returns x rounded to the integer nearest to it but no larger in magnitude