C++ Floor Function: Complete Guide

In C++, the floor function is a mathematical function used to return the largest integer value less than or equal to a specified floating-point number.

Here is how to use the floor function:

#include <iostream>
#include <cmath>

int main() {
    double x = 2.7;
    double y = -3.4;
    
    // 返回小于或等于x的最大整数值,结果为2
    std::cout << "floor(" << x << ") = " << floor(x) << std::endl;
    
    // 返回小于或等于y的最大整数值,结果为-4
    std::cout << "floor(" << y << ") = " << floor(y) << std::endl;
    
    return 0;
}

Output result:

floor(2.7) = 2
floor(-3.4) = -4

To use the floor function, you need to include the header file . When you pass a floating-point number as a parameter to the function, the floor function will return the largest integer value less than or equal to that floating-point number.

bannerAds