📅  最后修改于: 2023-12-03 15:13:54.157000             🧑  作者: Mango
The floor()
function in C++ is used to round down a given floating-point number to its nearest integer less than or equal to the given number. It's declared in the <cmath>
header file.
The syntax for using the floor()
function is as follows:
double floor(double x);
Here, x
is the floating-point number that needs to be rounded down to its nearest integer.
Let's consider an example to understand how the floor()
function works.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 4.6;
cout << "The floor of " << x << " is " << floor(x) << endl;
x = 2.3;
cout << "The floor of " << x << " is " << floor(x) << endl;
x = -3.4;
cout << "The floor of " << x << " is " << floor(x) << endl;
return 0;
}
Output:
The floor of 4.6 is 4
The floor of 2.3 is 2
The floor of -3.4 is -4
In the above example, we've used the floor()
function to round down the given floating-point numbers to their nearest integers. As we can see, the function returns the nearest integer less than or equal to the given number.
In conclusion, the floor()
function is a useful function in C++ for rounding down floating-point numbers to their nearest integer. It's simple to use and comes in handy when dealing with mathematical operations that require integer values.