In C, what is the difference between these two?
float myF = 5.6; printf( "%i \n", (int)myF ); // gives me "5" printf( "%ld \n", floor(myF) ); // also "5"?
When is one preferable over the other?
Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0. Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal. Save this answer.
C floor() The floor() function calculates the nearest integer less than the argument passed.
The ceil function and the floor function have different definitions. The ceil function returns the smallest integer value which is greater than or equal to the specified number, whereas the floor function returns the largest integer value which is less than or equal to the specified number.
int(x) is a functional notation for type-casting. C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion, known in C++ as type-casting.
One big difference is that of negative numbers; if you change myF
to -5.6
, then casting to an int returns -5
while floor(myF)
is -6
.
As to which is preferable, as a rule of thumb I'd say to only cast to an int if you know that's what you need -- and since you're asking here, chances are that you probably want floor
.
(Also note that with printf
formatting, %ld
is a long integer; a double is %lf
.)
floor(n)
returns the mathematical floor of n
, that is, the greatest integer not greater than n
. (int)n
returns the truncation of n
, the integer whose absolute value is no greater than that of n
. Similarly, ceil(n)
returns the mathematical ceiling of n
, or the smallest integer not smaller than n
. As AraK pointed out, the number returned by floor()
or ceil()
may not fit within the range of int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With