明晰C语言中的floor, ceil和type cast

floor, ceil and type cast

  1. 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 );
  2. 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 );
  3. type cast -- 强制类型转换,包括很多种的类型转换,能将一个对象显示的转换为另外特定的类型,在这里主要讨论数值之间的转换,如float, double 到 int 之间的转换。(int)(x),x为float或double类型,强制类型转换之后,返回x的整数部分。
  4. 在CRT中,并没有提供round(x) 函数(四舍五入),来求得与x值最接近的整数。但可以通过强制类型转换来实现round()函数的功能。(int)(x + ((x > 0) ? 0.5 : (-0.5))),其中x为float或double类型。
  5. 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;
    }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值