天天看点

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型运算自动向下取整。

继续阅读