當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ floor()用法及代碼示例

C++ floor() 函數

floor() 函數是 cmath 頭文件的庫函數,用於查找給定數字的向上(向下)取整值,它接受一個數字並返回不大於給定數字的最大整數值。

floor() 函數的語法:

    floor(x);

參數: x– 是要四舍五入其值的數字。

返回值: double– 它返回 double 類型的值,它是給定數字的四舍五入值。

例:

    Input:
    float x = 2.3;
    Function call:
    floor(x);
    Output:
    2

    Input:
    float x = 3.8
    Function call:
    floor(x);
    Output:
    3

C++代碼演示floor()函數的例子

// C++ code to demonstrate the example of 
// floor() function

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

// main() section
int main()
{
    float x;
    
    //input the number
    cout<<"Enter a float value:";
    cin>>x;
    
    //printing the round up value
    cout<<"floor("<<x<<"):"<<floor(x)<<endl;

    return 0;
}

輸出

First run:
Enter a float value:2.3 
floor(2.3):2

Second run:
Enter a float value:3.8 
floor(3.8):3 

Third run:
Enter a float value:-2.3
floor(-2.3):-3

Fourth run:
Enter a float value:-3.8
floor(-3.8):-4 


相關用法


注:本文由純淨天空篩選整理自 floor() function with example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。