c/c++之四舍五入函数

1. 在开发中,难免会遇到这样的情况,即需要对某段时间范围内的数据进行求和并取其平均值。这样就会涉及到小数的取舍问题。
比如:web需要通过REST协议向存储发起一个请求(该请求报文中有:起始时间、终止时间、人数、排队时间等)以获取某段时间范围内的数据,并且 存储需要返回该请求报文时间段内的:平均人数、平均排队等待的时间。那么现在需要考虑下面这几种情况:
(1)存储返回给web的平均人数必须得为整数,因为人不可能为小数。
(3)若平均人数大于0.5,但是小于1.0,那么该如何取舍。
(3)平均时间是可以取小数的,但是web希望收到的数据为整数。

若不采用c/c++库提供的函数,而直接用除法的话,则会事与愿违的,如下:

/*************************************************************************
 * File Name: floor.cpp
 * Author:    The answer
 * Function:  Other        
 * Mail:      [email protected] 
 * Created Time: 2018年05月22日 星期二 06时50分21秒
 ************************************************************************/

#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc,char **argv)
{
    int totalPeople = 15; 
    int sumNum      = 50; 
    int avgPeople   = totalPeople / sumNum;
    printf("avgPeople[%d]\n",avgPeople);
    return 0;
}

打印结果:avgPeople[0],显然不满足要求。

2. floor、ceil和round函数

函数名称 说明 3.2 3.6 -1.2 -2.9
floor 不大于自变量的最大整数 3 3 -2 -3
ceil 不小于自变量的最大整数 4 4 -1 -2
round 四舍五入到最邻近的整数 3 4 -1 -3

① floor 函数举例

#include <stdio.h>      /* printf */
#include <math.h>       /* 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;
}

打印结果:
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.


② ceil 函数举例

#include <stdio.h>      /* printf */
#include <math.h>       /* 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;
}

打印结果:
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

③ round 函数举例

#include <stdio.h>      /* printf */
#include <math.h>       /* 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;
}

打印结果:
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

猜你喜欢

转载自blog.csdn.net/lixiaogang_theanswer/article/details/80768250
今日推荐