c++四捨五入函式,向上取整,向下取整函式
阿新 • • 發佈:2019-01-09
對含有小數點的數進行四捨五入是比較普遍的一種需求。在C++中也有類似的取整函式。在C++的標頭檔案中有floor()和ceil()函式。在STL中還有round()函式。這三個函式的作用如下:
函式名稱 | 函式說明 | 2.1 | 2.9 | -2.1 | -2.9 |
Floor() | 不大於自變數的最大整數 | 2 | 2 | -3 | -3 |
Ceil() | 不小於自變數的最大整數 | 3 | 3 | -2 | -2 |
Round() | 四捨五入到最鄰近的整數 | 2 | 3 | -2 | -3 |
從函式說明中可以看出,
(1) Floor()會取不大於自變數的最大整數,這樣自變數是3.1或3.9是沒有區別的,返回都是3;自變數是-2.1或-2.9也是沒有區別的,返回都是-3;
(2) Ceil()會取不小於自變數的最大整數,這樣自變數是3.1或3.9,返回都是4;自變數是-2.1或-2.9,返回的都是-2;
(3) Round()函式,才是我們需要的四捨五入的函式,因為它會返回離自變數最近的整數,這個返回的整數可能大於也可能小於原來的數,但是一定是離它最近的那個整數。
double floor (double x); float floor (float x); long double floor (long double x); double floor (T x); // additional overloads for integral types
|
|
Output:
floor of 2.3 is 2.0 floor of 3.8 is 3.0 floor of -2.3 is -3.0 floor of -3.8 is -4.0 |
double ceil (double x); float ceil (float x); long double ceil (long double x); double ceil (T x); // additional overloads for integral types
|
|
Output:
ceil of 2.3 is 3.0 ceil of 3.8 is 4.0 ceil of -2.3 is -2.0 ceil of -3.8 is -3.0
double round (double x); float round (float x); long double round (long double x); double round (T x); // additional overloads for integral types
|
Output:
value round floor ceil trunc ----- ----- ----- ---- ----- 2.3 2.0 2.0 3.0 2.0 3.8 4.0 3.0 4.0 3.0 5.5 6.0 5.0 6.0 5.0 -2.3 -2.0 -3.0 -2.0 -2.0 -3.8 -4.0 -4.0 -3.0 -3.0 -5.5 -6.0 -6.0 -5.0 -5.0具體可檢視文獻:http://www.cplusplus.com/reference/cmath/round/