floor function in C

The floor function in C computes the largest integer value not greater than x. In other words, you can say that the floor function computes the largest integer value not greater than  x. The x is the argument that is passed into the floor().

It is declared in math.h and takes one argument in the form of double and returns the value of type double.

Example,

Input : 3.5
Output : 3


Input : -2.6
Output : -3


Input : 5.9
Output : 5

 

Syntax of floor function in C:

//Syntax of floor function in c

double floor(double x);

Parameters:

x => floating types (double)

Return value:

The floor functions return ⌊x⌋, expressed as a floating-point number.

 

You can use the floorf() function to work specifically with float and floorl() to work with long double type. See the below syntax.

//Syntax of other floor functions in C

float floorf(float x);

long double floorl(long double x);

 

C program to understand the working of floor function:

Below mentioned C example code shows the usage of floor().

#include <stdio.h>
#include <math.h>

int main ()
{
    double val1, val2, val3, val4;
    val1 = 3.5;
    val2 = -2.3;
    val3 = 3.8;
    val4 = 4.9;
  
    printf ("value1 = %.1lf\n", floor(val1));
    printf ("value2 = %.1lf\n", floor(val2));
    printf ("value3 = %.1lf\n", floor(val3));
    printf ("value4 = %.1lf\n", floor(val4));
  
    return(0);
}

Output:

value1 = 3.0
value2 = -3.0
value3 = 3.0
value4 = 4.0

 

Error handling

Errors are reported as specified in math_errhandling.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If arg is ±∞, it is returned, unmodified.
  • The current rounding mode has no effect.
  • If arg is ±0, it is returned, unmodified.
  • If arg is NaN, NaN is returned.
#include <math.h>
#include <stdio.h>

int main(void)
{
    printf("floor(-0.0) = %+.1f\n", floor(-0.0));

    printf("floor(-Inf) = %+f\n",   floor(-INFINITY));

    return 0;
}

Output:

floor(-0.0) = -0.0
floor(-Inf) = -inf

 

Recommended Post: