C Floor Function: Purpose & Examples

The floor function is a mathematical function in the C language standard library that rounds down by returning the largest integer less than or equal to the input parameter. This means that the floor function discards the decimal part of the input parameter and only retains the integer part. For example, the result of floor(3.14) would be 3.

The floor function is located in the header file, with a prototype of double floor(double x). It takes a double type parameter x and returns a double type result.

Specifically, the floor function rounds down the input parameter x, finding the largest integer that is not greater than x. If x is a positive number, floor(x) will return the largest integer not greater than x; if x is a negative number, floor(x) will return the largest integer not smaller than x. In mathematics, the floor function is commonly used in calculations that require rounding down, such as handling currency, calculating array indices, etc.

For example:

  1. The result of rounding down 3.14 is 3.0.
  2. The result of rounding -2.5 down is -3.0.
  3. The result of rounding down 5.8 is 5.0.

Using the floor function ensures that you will obtain an integer value that is less than or equal to the current value, without rounding up or approximating in any other way.

bannerAds