Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 300
igul222 Avatar asked Apr 08 '10 23:04

igul222


People also ask

What is the difference between int and floor?

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.

What is floor () in C?

C floor() The floor() function calculates the nearest integer less than the argument passed.

What is the difference between ceil () and floor () with examples?

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.

What does int x mean in C?

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.


2 Answers

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

like image 161
Mark Rushakoff Avatar answered Sep 20 '22 12:09

Mark Rushakoff


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.

like image 39
Jon Purdy Avatar answered Sep 17 '22 12:09

Jon Purdy