floor() Function
The floor()
function in C rounds a given value downward to the nearest integral value, effectively reducing the number to the next lower whole number if it is not already an integer. This operation is useful for converting floating-point numbers into whole numbers in a predictable manner.
Syntax of floor()
double floor(double x);
float floorf(float x);
long double floorl(long double x);
Parameters
Parameter | Description |
---|---|
x | The value to be rounded down. |
The function returns the largest integer value that is not greater than the provided value, and the result is of the same floating-point type as the input. It is important to note that even if the input value is already an integer, it is still returned as a floating-point number.
Examples for floor()
Example 1: Rounding Down a Positive Floating-Point Number
This example demonstrates how floor()
rounds a positive number downward.
Program
#include <stdio.h>
#include <math.h>
int main() {
double num = 3.7;
double result = floor(num);
printf("Original number: %.2f\n", num);
printf("After applying floor(): %.2f\n", result);
return 0;
}
Explanation:
- A double variable
num
is initialized with the value 3.7. - The
floor()
function is applied tonum
to round it down to the nearest whole number, resulting in 3.0. - The original and the rounded values are printed to the console.
Program Output:
Original number: 3.70
After applying floor(): 3.00
Example 2: Rounding Down a Negative Floating-Point Number
This example demonstrates how floor()
behaves when applied to a negative number, rounding it downward to a more negative integer.
Program
#include <stdio.h>
#include <math.h>
int main() {
double num = -3.2;
double result = floor(num);
printf("Original number: %.2f\n", num);
printf("After applying floor(): %.2f\n", result);
return 0;
}
Explanation:
- A double variable
num
is initialized with the value -3.2. - The
floor()
function is applied tonum
, which rounds it down to -4.0 because -4 is the largest integer less than -3.2. - The original and the rounded values are printed to the console.
Program Output:
Original number: -3.20
After applying floor(): -4.00