1. 程式人生 > >c++取整之ceil、floor、round、fix用法

c++取整之ceil、floor、round、fix用法

標頭檔案: #include <cmath>

一、ceil函式

朝上取整。

ceil(-3.14) = -3;
ceil(4.56) = 5;

二、floor函式

朝下取整。

floor(-3.14) = -4;
floor(4.56) = 4;

三、fix函式

朝0取整。

fix(-3.14) = -3;
fix(4.56) = 4;

四、round函式

四捨五入。

round(-3.14) = -3;
round(4.56) = 5;

五、整除

C/C++中的整數除法運算子“/”本身就有取整功能,整數除法對正數的取整是捨去小數部分。
但是整數除法對負數的取整結果和使用的C編譯器有關。

以VS2013編譯器為例,其處理整數除法對於正負數均採用捨去小數部分(類似於fix函式)

cout << 7/2 ;             // 2
cout << 8/2;              // 2
cout << -7/2;             // -2
cout << -8/2;             // -2