Function floor() in C++

floor Function of cmath Header File in C++

On this page we will discuss about function floor() which is used in C++. The cmath header file is a C++ standard library header file that contains a set of math functions and macro definitions that are used to perform mathematical operations. The floor function is used to calculate the greatest integer that is less than or equal to a given number.
floor() in c++

floor() Function in C++

In C++ programming language the floor function is included in cmath header file.

The floor function can handle values of any finite or infinite magnitude within the range of the double type in C++. The datatype of parameter can be double/ float/ long double only.

Declaration of floor function

double floor(double x) 

Parameters of floor function

The round function takes a single parameter x.
Parameter Description
x It is the number for which you want to calculate the floor.

Return value of floor function

The floor function in C++ returns the greatest integer that is less than or equal to a given number. The return value is of type double, even if the input is an integer.

Implementation of floor function in C++

Example 1:

The following code shows the use of floor function.
Run
#include  
#include 
using namespace std;

int main() {
    
  // Initialization of different parameters    
  double x = 3.14;
  cout << "floor of " << x << " is " << floor(x) << endl;

  x = -3.14;
  cout << "floor of " << x << " is " << floor(x) << endl;

  x = 3.9;
  cout << "floor of " << x << " is " << floor(x) << endl;

  x = -3.9;
  cout << "floor of " << x << " is " << floor(x) << endl;

  x = 3.0;
  cout << "floor of " << x << " is " << floor(x) << endl;

  x = -3.0;
  cout << "floor of " << x << " is " << floor(x) << endl;

  return 0;
}

Output:

floor of 3.14 is 3
floor of -3.14 is -4
floor of 3.9 is 3
floor of -3.9 is -4
floor of 3 is 3
floor of -3 is -3
If the input number is already an integer, the result will be the same as the input. If the input number is negative, the result will be the next smallest integer as seen in above example.

Example 2:

Run
#include <iostream>
#include <cmath>
using namespace std;

int main() {
  
  double result;

  // Initializing parameter x
  int x = 20;
  result = floor(x);

  cout << "Floor of " << x << " = " << result;

  return 0;
}

Output:

Floor of 20 = 20

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription