floor, ceil and type cast
- floor(x): returns a floating-point value representing the largest integer that is less than or equal to x。(返回不大于x的最大整数的浮点值)。调用时需包含math.h。函数原型如下:
double floor( double x );
float floor( float x ); // C++ only
long double floor( long double x ); // C++ only
float floorf( float x ); - ceil(x):returns a double value representing the smallest integer that is greater than or equal to x。(返回大于等于x的最小整数的浮点值)。调用时也需包含math.h。函数原型如下:
double ceil( double x );
float ceil( float x ); // C++ only
long double ceil( long double x ); // C++ only
float ceilf( float x ); - type cast -- 强制类型转换,包括很多种的类型转换,能将一个对象显示的转换为另外特定的类型,在这里主要讨论数值之间的转换,如float, double 到 int 之间的转换。(int)(x),x为float或double类型,强制类型转换之后,返回x的整数部分。
- 在CRT中,并没有提供round(x) 函数(四舍五入),来求得与x值最接近的整数。但可以通过强制类型转换来实现round()函数的功能。(int)(x + ((x > 0) ? 0.5 : (-0.5))),其中x为float或double类型。
- code example:
#include < stdio.h >
#include < math.h >
int main( int argc, char * argv[])
... {
float i = 3.1, j = 3.7, k = -3.1, m = -3.7;
//type cast, 3 3 -3 -3
printf("%d %d %d %d ", (int)i, (int)j, (int)k, (int)m);
//floor(), 3.000000 3.000000 -4.000000 -4.000000
printf("%f %f %f %f ", floor(i), floor(j), floor(k), floor(m));
//ceil(), 4.000000 4.000000 -3.000000 -3.000000
printf("%f %f %f %f ", ceil(i), ceil(j), ceil(k), ceil(m));
//round, 3 4 -3 -4
printf("%d %d %d %d", (int)(i + ((i > 0) ? 0.5 : (-0.5))), (int)(j + ((j > 0) ? 0.5 : (-0.5))),
(int)(k + ((k > 0) ? 0.5 : (-0.5))), (int)(m + ((m > 0) ? 0.5 : (-0.5))));
return 1;
}