In mathematics and computer science, the floor() and ceil() functions that are defined in <cmath> header file, map a real number to the greatest preceding or the least succeeding integer, respectively.
C++ floor() Function
The floor() function returns the largest integer that is smaller than or equal to the value passed as the argument (i.e.: rounds down the nearest integer).
floor() Syntax
double floor(double x);
Here x is the floating point value. It returns the largest integer smaller than or equal to x.
Example of the floor of some floating point values:
Input : 2.5
Output : 2
Input : -2.1
Output : -3
Example
CPP
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << "Floor of 2.3 is : " << floor (2.3) << endl;
cout << "Floor of -2.3 is : " << floor (-2.3) << endl;
return 0;
}
|
Output
Floor of 2.3 is : 2
Floor of -2.3 is : -3
C++ ceil() Function
ceil() function in C++ returns the smallest integer that is greater than or equal to the value passed as the argument (i.e.: rounds up the nearest integer).
Syntax of ceil()
double ceil(double x);
Here x is the floating point value. It returns the smallest integer greater than or equal to x.
Example of ceil of some floating point values:
Input : 2.5
Output : 3
Input : -2.1
Output : -2
Example
C++
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
cout << " Ceil of 2.3 is : " << ceil (2.3) << endl;
cout << " Ceil of -2.3 is : " << ceil (-2.3) << endl;
return 0;
}
|
Output
Ceil of 2.3 is : 3
Ceil of -2.3 is : -2
Time Complexity: O(1)
Auxiliary Space: O(1)
Difference between ceil() and floor() in C++
Let us see the differences between ceil() and floor() functions in tabular form:
S.No
|
ceil() Function
|
floor() Function
|
1.
|
It is used to return the smallest integral value n that is not less than n. |
It is used to return the largest integral value n that is not greater than n. |
2.
|
It rounds the n upwards. |
It rounds the n downwards. |
3.
|
Its syntax is -:
data_type ceil (n);
|
Its syntax is -:
data_type floor (n);
|
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 May, 2023
Like Article
Save Article