C语言中的小数取整和四舍五入

将小数直接抹掉的取整

1自动类型转换


例如 :

 #include <stdio.h> 
main()
{
         int a;
         a=2.7;
         printf("a = %d",a);
}          //   a = 2

2强制类型转换


例如:

#include <stdio.h>
main()
{
         printf("%d",(int)3.75);   //输出结果为 3
}

四舍五入取整

强转实现四舍五入

#include <stdio.h>
main()
{
        int a ,b;
        a = (int)(3.2+0.5);
        b = (int)(5.6+0.5);
        printf("a=%d,b=%d",a,b);
        //a=3,b=6
}      

(int)(3.2+0.5)=(int)3.7=3
(int)(5.6+0.5)=(int)6.1=6

其它取整方法

ceil函数


ceil(x)返回的大于等于x的最小整数

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
         int a,b,c,d;
         a = ceil(1.7);
         b = ceil(2.3);
         c = ceil(-2.3);
         d = ceil(8.0);
         printf("a = %d,b = %d,c = %d,d = %d",a,b,c,d);
}

在这里插入图片描述

floor 取出小于等于x的最大整数


floor()和ceil()函数均在math.h头文件中定义

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
         int a,b,c,d;
         a = floor(1.7);
         b = floor(2.3);
         c = floor(-2.3);
         d = floor(8.0);
         printf("a = %d,b = %d,c = %d,d = %d",a,b,c,d);
}

在这里插入图片描述
强制类型转换,效果不一定等同于floor函数例如(int)-2.3=-2而floor(-2.3)=-3

  • 12
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值