C programming floor , floorf and floorl math.h


In C programming the <math.h> floor,floorf and floorl function compute the largest integer value not greater than the argument.The declaration of the functions are given below.

1 float floor(float x);
2 double floor(double x);
3 long double floor(long double x);
4 float floorf(float x);
5 long double floorl(long double x);

Parameters:
x -The argument whose largest integer is to be computed.

Return type
floating point -The largest integer value not greater than x.

All the functions are the same,they compute the largest integer value not greater x.The 1st,2nd and the 3rd function have the same name i.e.’floor’.The 4th and 5th function have different names.What does having a different names mean is explained in detail below.

Some points to note:

  i) floor(x) is same as C floor similarity.

  ii) If ±0 is passed ±0 is returned.

  iii) If NAN is passed ‘nan’ is returned.

  iv) If ±∞ is passed ±∞ is returned.

Using floor function to convert the floating point type to int type is safer than using the casting method,due to it safer way of handling the floating point value without causing any overflow.Note in x-axis the floor function round the argument to the nearest integer in the left direction.

C floor,floorf ,floorl

Code example

double d=1.234 , x1=2.9877800e20 ;

float f=1.234 ;

long double ld=1.234 ;

printf(“%lf”, floor( d ) ) ; //calls the 2nd version
printf(“\n%f”, floor( f ) ) ; //calls the 1st version
printf(“\n%Lf”, floor( ld ) ) ;//calls the 3rd version

printf(“\n%lf”, floor( x1 ) ) ;
printf(“\n%lf”, floor( NAN ) ) ;

Output in Visual Studio ,

1.000000
1.000000
1.000000
298778000000000000000.000000
-nan(ind)


 


floorf

The ‘floorf‘ function is same as the 1st function.This means the parameter and return type of the function is float type.The ‘f‘ character appended to ‘floorf‘ stands for float and it signify the parameter type and return type of the function.

Code example

float x=50.01 ;

printf(“%f”, floor( x ) ); //Calls the 1st version
printf(“\n%f”, floorf( 50.01) ); Calls the 4th version

Output in Visual Studio,

50.000000
50.000000


floorl

The ‘floorl‘ function is same as the 1st function.This means the parameter and return type of the function is long double type.The ‘l‘ character appended to ‘floorl‘ stands for long double and it signify the parameter type and return type of the function.

Code example

long double x=50.01;

printf(“%Lf”, floor( x ) ); //Calls the 3rd version
printf(“\n%Lf”, floorl( 50.01 ) ); Calls the 5th version

Output,

50.000000
50.000000


Related links

C ceil,ceilf and ceill math.h