首先我们需要知道C标准库中是有向上/下取整的函数的,需要引入math.h,但是是否有四舍五入的函数(即round()函数),取决于你的编译器是否支持C99标准!不过不用担心,即使你的编译器不支持,我这里也会提供给你一种方式来解决四舍五入的问题。
1. 向上取整
1.1 函数解析
C语言中向上取整的函数为ceil(),
ceil(x)返回的是大于x的最小整数
所以对于正数,1.2向上取整为2;对于负数,-1.2向上取整为-1
(不会吧不会吧,不会真有人搞不清负数谁大谁小吧[狗头][狗头])
——————————————————————————>
−
∞
-\infty
−∞ … -3 -2 -1 0 1 2 3 …
+
∞
+\infty
+∞
ceiling的意思是天花板,可与向上取整自行脑补一下
原型:double ceil(doube x);
返回值:
成功:返回一个double类型的数,此数默认有6位小数
无失败的返回值
1.2 举例
#include <stdio.h>
#include <math.h>
int main()
{
double i = ceil(2.45);
double j = ceil(-2.45);
printf("%f\n%f\n",i,j);
}
//输出结果为:3.000000 -2.000000
2. 向下取整
2.1 函数解析
C语言中向下取整的函数为floor(),
floor(x)返回的是小于x的最大整数
所以对于正数,1.2向下取整为1;对于负数,-1.2向下取整为-2
floor的意思是地板,可与向下取整自行脑补一下
原型:double floor(doube x);
返回值:
成功:返回一个double类型的数,此数默认有6位小数
无失败的返回值
2.2 举例
#include <stdio.h>
#include <math.h>
int main()
{
double i = floor(2.45);
double j = floor(-2.45);
printf("%f\n%f\n",i,j);
}
//输出结果为:2.000000 -3.000000
3. 四舍五入
3.1 函数解析
如果说你的编译器支持C99标准,那么可以直接用round()函数;
该函数的作用就是将一个小数四舍五入为整数;
原型:double round(doube x);
round的意思是附近,可与四舍五入自行脑补一下
3.2 举例
#include <stdio.h>
#include <math.h>
int main()
{
double i = round(2.45);
double j = round(-2.45);
printf("%f\n%f\n",i,j);
}
//输出结果为:2.000000 -2.000000
//大家可考虑下我为什么用2.45这个值
3.3 其他方法
如果说编译器不支持C99,那么我们就需要自行设计一个函数来完成四舍五入的功能。
int Rounding(double x)
{
return x>0 ? (int)(x+0.5) : (int)(x-0.5);
}
int main()
{
double i = Rounding(2.45);
double j = Rounding(-2.45);
printf("%f\n%f\n",i,j);
}
//输出结果为:2.000000 -2.000000
4. int
关于int,其实很简单,直接“屏蔽”整数后面的小数
如: int(2.45) 结果为2,int(-2.45)结果为-2
额外补充:
运算符 ‘ / ’,即整除,其实也是向下取整的(注意除数和被除数都是int型)