1. 程式人生 > >iOS常用數學方法

iOS常用數學方法

(1)向上取整 

extern float ceilf(float);
extern double ceil(double);
extern long double ceill(long double);

示例:

ceilf(3.9)=4
ceilf(3.1)=4
ceilf(-3.1)=-3
ceilf(-3.9)=-3

(2)向下取整

extern float floorf(float);
extern double floor(double);
extern long double floorl(long double);

示例:

floorf(3.9)=3
floorf(3.1)=3
floorf(-3.9)=-4
floorf(-3.1)=-4

(3)四捨五入

extern float roundf(float);
extern double round(double);
extern long double roundl(long double);

示例

roundf(3.5)=4
roundf(3.4)=3
roundf(-3.4)=-3
roundf(-3.5)=-4

(4)最接近引數的整數,如果有兩個就取偶數

extern float nearbyintf(float);
extern double nearbyint(double);
extern long double nearbyintl(long double);

extern float rintf(float);
extern double rint(double);
extern long double rintl(long double);

extern long int lrintf(float);
extern long int lrint(double);
extern long int lrintl(long double);

示例

rintf(3.6)=4
rintf(3.5)=4
rintf(3.4)=3

rintf(2.6)=3
rintf(2.5)=2
rintf(2.4)=2

rintf(-2.4)=-2
rintf(-2.5)=-2
rintf(-2.6)=-3

rintf(-3.4)=-3
rintf(-3.5)=-4
rintf(-3.6)=-4

(5)去除小數位

extern float truncf(float);
extern double trunc(double);
extern long double truncl(long double);

示例

truncf(3.9)=3
truncf(3.1)=3
truncf(-3.1)=-3
truncf(-3.9)=-3