floor() Function Example in C Programming

In this source code example, we will see how to use the floor() function in C programming with an example.

floor() Function Overview

The floor() function in C returns the largest integer value that is not greater than the argument. In simpler terms, it rounds down any decimal number to the nearest whole number. This function is particularly beneficial when needing an approximation towards the lower integer, such as in certain mathematical calculations or algorithms. The function is located within the math.h library.

Key Points:

- The math.h header must be included to make use of the floor() function.

- The function rounds down the decimal number, returning the closest lesser integer or the number itself if it's already an integer.

- Don't forget to link the math library using the -lm flag while compiling.

Source Code Example

``````#include <stdio.h>
#include <math.h>  // Necessary for floor()

int main() {
double value, result;

// Ask the user for input
printf("Enter a decimal value: ");
scanf("%lf", &value);

// Use the floor() function to round down the value
result = floor(value);

// Display the rounded down value
printf("The floor value of %.2lf is: %.0lf\n", value, result);

return 0;
}
``````

Output

```Enter a decimal value: 4.7
The floor value of 4.70 is: 4
```

Explanation

1. We start off by incorporating the necessary header files: stdio.h for basic input/output operations and math.h for the floor() function.

2. In the main() function, we prompt the user to input a decimal value.

3. The floor() function then rounds down the provided value to its nearest integer.

4. The result, after rounding down, is printed to the console.