天天看點

Ceil、Floor、round 函數

C中常用的三種取整函數:ceil、floor、round。
頭檔案:#include<math.h>

ceil:

表示向上取整,比如5.1,取整之後為6,即 5<x<=6 ,取整之後就是6。

用法:

指派中用
double x=5.1;
double c=ceil(x);

或在運算中用:
if(c<ceil(x))
{
}

           

floor:

表示向下取整,比如5.1,取整之後為5,即 5<=x<6 ,取整之後就是5。

用法同上。

round:

表示四舍五入運算,與數學中的四舍五入一樣,eg: 5.4=5,5.6=6.

用法同上。

其他的四舍五入技巧:

1.

double x;

int n;

n = int(x+0.5);

2.運算中的取一半的四舍五入

int x;

x=x/2+x%2;

注:當用ceil,floor,round 函數時,數值類型用double或float等浮點型,用int型會自動忽略小數點後的數,會導緻函數使用失敗(非文法錯誤),int型運算自動向下取整。

繼續閱讀