C library - floor() function



The C library floor() function of type double accept the single parameter(x) to return the largest integer value less than or equal to, by the given values.

This function rounds a number down to the nearest integer multiple of the specified significance.

Syntax

Following is the syntax of the C library function floor()

double floor(double x)

Parameters

This function takes only a single parameter −

  • x − This is the floating point value.

Return Value

This function returns the largest integral value not greater than x.

Example 1

Following is the basic C library example to see the demonstration of floor() function.

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

int main () {
   float val1, val2, val3, val4;

   val1 = 1.6;
   val2 = 1.2;
   val3 = 2.8;
   val4 = 2.3;

   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);
}

The above code produces the following result −

Value1 = 1.0
Value2 = 1.0
Value3 = 2.0
Value4 = 2.0

Output

Example 2

Below the program shows how to use floor() to round down a value.

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

int main() {
   double num = 8.33;
   double result = floor(num);

   printf("Floor integer of %.2lf = %.0lf\n", num, result);
   return 0;
}

On execution of above code, we get the following result −

Floor integer of 8.33 = 8

Output

Example 3

Here, we generate the table of integer using floor() and this table ranges of positive floating-point numbers.

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

int main() {
   double start = 6.5;
   double end = 9.5;

   printf("Table of Floor Integers:\n");
   for (double num = start; num <= end; num += 1.0) {
       double result = floor(num);
       printf("Floor(%.2lf) = %.0lf\n", num, result);
   }

   return 0;
}

Output

After excuting the above code, we get the following result −

Table of Floor Integers:
Floor(6.50) = 6
Floor(7.50) = 7
Floor(8.50) = 8
Floor(9.50) = 9
Advertisements