C++ 中的向上取整和向下取整函式


ceil 函式

ceil 函式返回等於或大於該值的最小整數。此函式在 C++ 語言中宣告在 “cmath” 標頭檔案中。它接受一個需要計算其向上取整值的單一值。變數的資料型別只能是 double/float/long double。

以下是 C++ 語言中 ceil 函式的語法:

double ceil(double x);
float ceil(float x);

以下是 C++ 語言中 ceil 函式的示例:

示例

 線上演示

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float var = 1234.25;
   float res;
   res = ceil(var);
   cout << "Ceil value of " << var << " = " << res << endl;
   return 0;
}

輸出

Ceil value of 1234.25 = 1235

floor 函式

floor 函式返回等於或小於該值的最大整數。此函式也在 C++ 語言的 “cmath” 標頭檔案中宣告。它接受一個需要計算其向下取整值的單一值。變數的資料型別只能是 double/float/long double。

以下是 C++ 語言中 floor 函式的語法:

double floor(double x);
float floor(float x);

以下是 C++ 語言中 floor 函式的示例:

示例

 線上演示

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float var = 211.876;
   float res;
   res = floor(var);
   cout << "Floor value of " << var << " = " << res << endl;
   return 0;
}

輸出

Floor value of 211.876 = 211

更新於:2020年6月24日

5K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.