C语言中四种取整方式
c语言中常见的四种取整方式:trunc(),floor(), ceil()和trunc()

1.trunc()函数:截断小数部分,放回整数部分 本质直接把小数部分丢掉,向0取整
参数:x 是要截断的浮点数(double 类型) 返回值:截断后的值(仍然是 double 类型,但小数部分为 0) #include <math.h> double trunc(double x);
/*******例子**********/ #include <stdio.h> #include <math.h> int main() { double num1 = 3.7; double num2 = -2.9; printf("trunc(3.7) = %.1f\n", trunc(num1)); // 输出 3.0 printf("trunc(-2.9) = %.1f\n", trunc(num2)); // 输出 -2.0 return 0; } 输出结果 trunc(3.7) = 3.0 trunc(-2.9) = -2.0
2:floor():用于 向负无穷方向取整(即向下取整)
-
对
x向下取整(向更小的整数方向舍入) -
返回类型:
double(即使结果是整数,也会返回3.0这样的浮点数)
#include <math.h> double floor(double x); // 标准 double 版本 float floorf(float x); // float 版本(C99) long double floorl(long double x); // long double 版本(C99)
与trunc()函数的区别在于负数的处理,trunc(x)直接丢掉小数部分,向0靠近,对于原数x来说变大的。而floor则是变得更小
3.ceil() 函数:向正无穷取整(向上取整)
对 x 向上取整(向更大的整数方向舍入) 返回类型:double(即使结果是整数,也会返回 4.0 这样的浮点数) #include <math.h> double ceil(double x); // 标准 double 版本 float ceilf(float x); // float 版本(C99) long double ceill(long double x); // long double 版本(C99)
4:round() 函数的:用于 四舍五入取整
对 x 四舍五入取整(即向最接近的整数舍入) 返回类型:double(即使结果是整数,也会返回 4.0 这样的浮点数) #include <math.h> double round(double x); // 标准 double 版本 float roundf(float x); // float 版本(C99) long double roundl(long double x); // long double 版本(C99)
#include <stdio.h> #include <math.h> int main() { printf("round(3.2) = %.1f\n", round(3.2)); // 3.0 printf("round(3.5) = %.1f\n", round(3.5)); // 4.0 printf("round(-2.3) = %.1f\n", round(-2.3)); // -2.0 printf("round(-2.8) = %.1f\n", round(-2.8)); // -3.0 return 0; }
浙公网安备 33010602011771号