In programming dealing with integer values is more manageable and straightforward than decimal values. Working with integer values is easy and helps get accurate results. In c++, we have the floor and ceil functions to solve this problem. Floor and Ceil in c++ are those functions that help provide the integer value nearest to that decimal value.
In this blog, we will learn about floor and Ceil in C++. Also see, Literals in C.
What is floor() in C++?
The floor is a function in c++ that is defined and described in the cmath header file.
- This function returns the largest possible integer that is equal to or smaller than the input number.
- It gives the downward value of the number.
- The floor() function takes a single input parameter and returns a single value integer.
floor() syntax in C++
The syntax is similar to a normal function.
floor(number);
The parameters of floor() function takes are shown below:
- int floor(int number);
- float floor(float number);
- double floor(double number);
- long double floor( long double number);
Return value
floor() returns the largest possible integer equal to or smaller than the input number.
Examples of floor()
- Input: 10.25 Output: 10
- Input: 111.89 Output: 111
- Input: -2.6 Output: -3
Program using floor() function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float num= 11.66;
float var = -3.6;
cout<<"floor value of the num is "<<floor(num)<<endl;
cout<<"floor value of the var is "<<floor(var)<<endl;
return 0;
}
Output
What is ceil() in C++?
Ceil is a function in c++ that is defined and described in the cmath header file.
- This function returns the smallest possible integer that is greater than or equal to the input number.
- It gives the upward value of the number.
- The ceil() function takes a single input parameter and returns a single value integer.
ceil() syntax in C++
ceil(number);
The parameters this function takes are shown below:
- int ceil(int number);
- float ceil(float number);
- double ceil(double number);
- long double ceil( long double number);
Return value
ceil() returns the smallest possible integer that is equal to or smaller than the input number.
Examples of ceil()
- Input: 10.5 Output: 11
- Input: 111.8 Output: 112
- Input: 3.7 Output: 4
Program using ceil() function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float num= 11.66;
float var = -3.6;
cout<<" Ceil value of the num is "<<ceil(num)<<endl;
cout<<" Ceil value of the var is "<<ceil(var)<<endl;
return 0;
}
Output
You practice by yourself with the help of online c++ compiler.