views:

216

answers:

5

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?

A: 

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.

R Samuel Klatchko
+1  A: 

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.

bdl
`Math.floor` is not in C.
Jon Purdy
Well, yes, you're technically correct. "Math.floor" is not in C. I think you know what I meant. Check my edit.
bdl
@bdl: Yeah, I did. Sorry if I came off as a jerk. This place tends to turn people a tad self-righteous...
Jon Purdy
+4  A: 

When you get the floor of double, that "integer" double may or mayn't be representable in a variable of type int.

AraK
+8  A: 

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.)

Mark Rushakoff
+2  A: 

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.

Jon Purdy