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?
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?
Do you want the result as an integer or a double?
If you want a integer, cast; if you want a double, use floor
.
For example, if you want to get the cosine of the value, you should just use floor
as cos
takes a double.
But if you wanted to use the value for exit
(just picking a random API here), you should cast because exit
takes an int.
The former casts your float value as a integer (and you're using an int specifier in the printf call).
The latter uses floor (from the C math lib) to return a double that has been rounded down.
When you get the floor
of double, that "integer" double
may or mayn't be representable in a variable of type int
.
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
.