C Programming: floor() Function 🎯

beginner
23 min

C Programming: floor() Function 🎯

Welcome to our comprehensive guide on the C floor() function! In this tutorial, we'll delve into what the floor() function is, why it's useful, and how to use it effectively in your C programs. Let's get started!

Introduction 📝

The floor() function in C is a built-in function that returns the largest integer not greater than the given floating-point number. It's part of the math.h library, so don't forget to include it at the beginning of your C programs!

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

Syntax 📝

The syntax for the floor() function is straightforward:

c
float floor(float number);

Here, number is the floating-point number you want to find the largest integer less than or equal to.

Example 1 💡

Let's see the floor() function in action with a simple example:

c
#include <stdio.h> #include <math.h> int main() { float num = 12.5; printf("The floor value of %.2f is %.0f\n", num, floor(num)); return 0; }

In this example, we have a floating-point number num with the value 12.5. When we use the floor() function, it returns the largest integer not greater than 12.5, which is 12.

Example 2 💡

Let's consider another example where we use the floor() function to round down a negative floating-point number:

c
#include <stdio.h> #include <math.h> int main() { float num = -12.7; printf("The floor value of %.2f is %.0f\n", num, floor(num)); return 0; }

In this example, the floor() function returns the largest integer less than or equal to -12.7, which is -13.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the `floor()` function in C used for?

Conclusion 📝

By now, you should have a good understanding of the C floor() function and its applications. With practice, you'll be able to effectively use it in your C programs to simplify calculations involving floating-point numbers. Happy coding! 🎉