Ceil and Floor functions in C++
C++ provides floor() and ceil() functions, defined in the <cmath> header file, to find the rounded-down and rounded-up values of floating-point numbers
floor() Function
floor() function takes floating point number as input and returns the largest integer that is smaller than or equal to the value passed as the argument.
Syntax:
floor(num);
Example:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// using floor function which
// return floor of input value
cout << "Floor of 2.3 is : "
<< floor(2.3) << endl;
cout << "Floor of -2.3 is : "
<< floor(-2.3);
return 0;
}
Output
Floor of 2.3 is : 2 Floor of -2.3 is : -3
ceil() Function
ceil() function in C++ returns the smallest integer that is greater than or equal to the value passed as the input argument.
Syntax:
ceil(num);
Example:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
// using ceil function which return
// floor of input value
cout << " Ceil of 2.3 is : "
<< ceil(2.3) << endl;
cout << " Ceil of -2.3 is : "
<< ceil(-2.3);
return 0;
}
Output
Ceil of 2.3 is : 3 Ceil of -2.3 is : -2
Difference between ceil() and floor() in C++
The ceil and floor functions are important for rounding numbers. 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); |