C++的ceil、floor和round用法解讀
在 C++ 中,向上取整(Ceiling)、向下取整(Floor)、四舍五入(Rounding) 可以通過標準庫 <cmath>
提供的函數(shù)實現(xiàn)。
1. 標準庫函數(shù)(推薦)
(1)std::ceil(x)—— 向上取整
功能:返回 ≥ x
的最小整數(shù)(即“天花板值”)。
頭文件:#include <cmath>
示例:
#include <cmath> #include <iostream> int main() { double x = 3.2; double y = -2.7; std::cout << std::ceil(x) << std::endl; // 輸出 4.0 std::cout << std::ceil(y) << std::endl; // 輸出 -2.0 return 0; }
(2)std::floor(x)—— 向下取整
功能:返回 ≤ x
的最大整數(shù)(即“地板值”)。
頭文件:#include <cmath>
示例:
#include <cmath> #include <iostream> int main() { double x = 3.7; double y = -2.3; std::cout << std::floor(x) << std::endl; // 輸出 3.0 std::cout << std::floor(y) << std::endl; // 輸出 -3.0 return 0; }
(3)std::round(x)—— 四舍五入
功能:返回最接近 x
的整數(shù)(四舍五入)。
頭文件:#include <cmath>
示例:
#include <cmath> #include <iostream> int main() { double x = 3.4; double y = 3.6; double z = -2.5; std::cout << std::round(x) << std::endl; // 輸出 3.0 std::cout << std::round(y) << std::endl; // 輸出 4.0 std::cout << std::round(z) << std::endl; // 輸出 -2.0(注意:-2.5 四舍五入為 -2) return 0; }
2. 手動實現(xiàn)(適用于整數(shù)運算)
(1)向上取整(Ceiling)
int ceil_division(int a, int b) { return (a + b - 1) / b; }
示例:
int x = 7, y = 3; int ceil = (x + y - 1) / y; // ceil = 3(因為 7/3 ≈ 2.333,向上取整得 3)
(2)向下取整(Floor)
int floor_division(int a, int b) { return a / b; }
示例:
int x = 7, y = 3; int floor = x / y; // floor = 2(因為 7/3 ≈ 2.333,向下取整得 2)
(3)四舍五入(Rounding)
int round_division(int a, int b) { return (a + b / 2) / b; }
示例:
int x = 7, y = 3; int rounded = (x + y / 2) / y; // rounded = 2(因為 7/3 ≈ 2.333,四舍五入得 2)
3. 注意事項
std::ceil
、std::floor
、std::round
返回 double
,如果需要整數(shù),需要顯式轉換:
int ceil_val = static_cast<int>(std::ceil(3.2)); // ceil_val = 4 int floor_val = static_cast<int>(std::floor(3.7)); // floor_val = 3 int round_val = static_cast<int>(std::round(3.6)); // round_val = 4
負數(shù)情況:
std::ceil(-2.3)
返回-2.0
(向上取整)。std::floor(-2.3)
返回-3.0
(向下取整)。std::round(-2.5)
返回-2.0
(四舍五入)。
編譯選項(某些編譯器可能需要 -lm
鏈接數(shù)學庫):
g++ program.cpp -o program -lm
4. 總結
方法 | 適用場景 | 示例 |
---|---|---|
std::ceil(x) | 標準向上取整(推薦) | std::ceil(3.2) → 4.0 |
std::floor(x) | 標準向下取整(推薦) | std::floor(3.7) → 3.0 |
std::round(x) | 標準四舍五入(推薦) | std::round(3.6) → 4.0 |
(a + b - 1) / b | 整數(shù)向上取整 | (7 + 3 - 1) / 3 = 3 |
a / b | 整數(shù)向下取整 | 7 / 3 = 2 |
(a + b / 2) / b | 整數(shù)四舍五入 | (7 + 1) / 3 = 2 |
推薦優(yōu)先使用 <cmath>
提供的標準函數(shù),它們更通用且可讀性更好。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C++中類的成員函數(shù)及內(nèi)聯(lián)函數(shù)使用及說明
這篇文章主要介紹了C++中類的成員函數(shù)及內(nèi)聯(lián)函數(shù)使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11