igul222
igul222

Reputation: 8637

C: difference between (int)x and floor(x)?

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?

Upvotes: 22

Views: 29447

Answers (5)

bdl
bdl

Reputation: 1502

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.

Upvotes: 1

Jon Purdy
Jon Purdy

Reputation: 54989

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.

Upvotes: 5

Mark Rushakoff
Mark Rushakoff

Reputation: 258228

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

Upvotes: 31

Khaled Alshaya
Khaled Alshaya

Reputation: 96879

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

Upvotes: 3

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

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.

Upvotes: 0

Related Questions