The floor()
function in C++ returns the largest possible integer value which is less than or equal to the given argument.
It is defined in the cmath header file.
Example
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// get the largest possible integer less than or equal to 68.95
cout << floor(68.95);
return 0;
}
// Output: 68
floor() Syntax
The syntax of the floor()
function is:
floor(double num);
floor() Parameters
The floor()
function takes the following parameters:
- num - a floating point number whose floor value is computed. It can be of the following types:
double
float
long double
floor() Return Value
The floor()
function returns:
- the largest possible integer value which is less than or equal to num
floor() Prototypes
The prototypes of the floor()
function as defined in the cmath header file are:
double floor(double num);
float floor(float num);
long double floor(long double num);
// for integral types
double floor(T num);
Example 1: C++ floor()
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num, result;
num = 10.25;
result = floor(num);
cout << "Floor of " << num << " = " << result << endl;
num = -34.251;
result = floor(num);
cout << "Floor of " << num << " = " << result << endl;
num = 0.71;
result = floor(num);
cout << "Floor of " << num << " = " << result;
return 0;
}
Output
Floor of 10.25 = 10 Floor of -34.251 = -35 Floor of 0.71 = 0
Example 2: C++ floor() for Integral Types
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double result;
int num = 15;
result = floor(num);
cout << "Floor of " << num << " = " << result;
return 0;
}
Output
Floor of 15 = 15
The floor of an integral value is the integral value itself, so the floor()
function isn't used on integral values in practice.