Ceil and Floor functions in C++
Last Updated :
24 May, 2023
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);
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...