c++四舍五入函数,向上取整,向下取整函数

时间:2024-11-08 07:12:38

对含有小数点的数进行四舍五入是比较普遍的一种需求。在C++中也有类似的取整函数。在C++的头文件中有floor()和ceil()函数。在STL中还有round()函数。这三个函数的作用如下:

           
函数名称 函数说明 2.1 2.9 -2.1 -2.9
Floor() 不大于自变量的最大整数 2 2 -3 -3
Ceil() 不小于自变量的最大整数 3 3 -2 -2
Round() 四舍五入到最邻近的整数 2 3 -2 -3

从函数说明中可以看出,
(1) Floor()会取不大于自变量的最大整数,这样自变量是3.1或3.9是没有区别的,返回都是3;自变量是-2.1或-2.9也是没有区别的,返回都是-3;
(2) Ceil()会取不小于自变量的最大整数,这样自变量是3.1或3.9,返回都是4;自变量是-2.1或-2.9,返回的都是-2;
(3) Round()函数,才是我们需要的四舍五入的函数,因为它会返回离自变量最近的整数,这个返回的整数可能大于也可能小于原来的数,但是一定是离它最近的那个整数。

double floor (double x);
      float floor (float x);
long double floor (long double x);
     double floor (T x);           // additional overloads for integral types

1
2
3
4
5
6
7
8
9
10
11
12
/* floor example */
#include <>      /* printf */
#include <>       /* floor */

int main ()
{
  printf ( "floor of 2.3 is %.1lf\n", floor (2.3) );
  printf ( "floor of 3.8 is %.1lf\n", floor (3.8) );
  printf ( "floor of -2.3 is %.1lf\n", floor (-2.3) );
  printf ( "floor of -3.8 is %.1lf\n", floor (-3.8) );
  return 0;
}

Output:


floor of 2.3 is 2.0
floor of 3.8 is 3.0
floor of -2.3 is -3.0
floor of -3.8 is -4.0
double ceil (double x);
      float ceil (float x);
long double ceil (long double x);
     double ceil (T x);           // additional overloads for integral types
1
2
3
4
5
6
7
8
9
10
11
12
/* ceil example */
#include <>      /* printf */
#include <>       /* ceil */

int main ()
{
  printf ( "ceil of 2.3 is %.1f\n", ceil(2.3) );
  printf ( "ceil of 3.8 is %.1f\n", ceil(3.8) );
  printf ( "ceil of -2.3 is %.1f\n", ceil(-2.3) );
  printf ( "ceil of -3.8 is %.1f\n", ceil(-3.8) );
  return 0;
}

Output:

ceil of 2.3 is 3.0
ceil of 3.8 is 4.0
ceil of -2.3 is -2.0
ceil of -3.8 is -3.0
 double round (double x);
      float round (float x);
long double round (long double x);
     double round (T x);           // additional overloads for integral types
/* round vs floor vs ceil vs trunc */
#include <>      /* printf */
#include <>       /* round, floor, ceil, trunc */

int main ()
{
  const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
  printf ("value\tround\tfloor\tceil\ttrunc\n");
  printf ("-----\t-----\t-----\t----\t-----\n");
  printf (format, 2.3,round( 2.3),floor( 2.3),ceil( 2.3),trunc( 2.3));
  printf (format, 3.8,round( 3.8),floor( 3.8),ceil( 3.8),trunc( 3.8));
  printf (format, 5.5,round( 5.5),floor( 5.5),ceil( 5.5),trunc( 5.5));
  printf (format,-2.3,round(-2.3),floor(-2.3),ceil(-2.3),trunc(-2.3));
  printf (format,-3.8,round(-3.8),floor(-3.8),ceil(-3.8),trunc(-3.8));
  printf (format,-5.5,round(-5.5),floor(-5.5),ceil(-5.5),trunc(-5.5));
  return 0;
}


Output:

value   round   floor   ceil    trunc
-----   -----   -----   ----    -----
2.3     2.0     2.0     3.0     2.0
3.8     4.0     3.0     4.0     3.0
5.5     6.0     5.0     6.0     5.0
-2.3    -2.0    -3.0    -2.0    -2.0
-3.8    -4.0    -4.0    -3.0    -3.0
-5.5    -6.0    -6.0    -5.0    -5.0
具体可查看文献:/reference/cmath/round/