Home C&C++函数库 c++ 语法 程序源码 Linux C库

round

函数  <cmath> <ctgmath>

C99 double round (double x);
float roundf (float x);
long double roundl (long double x);
C++11 double round (double x);
float round (float x);
long double round (long double x);
double round (T x);        // additional overloads for integral types

就近舍入
返回最接近x的整数值,中间情况趋零四舍五入。

C99 头文件<tgmath.h> 提供了该函数的类型泛型宏版本。
C++11 这个头文件(<cmath>)为整型提供了额外的重载: 这些重载有效地在计算之前将x转换为double(在T是任何整型时定义)。

☲  参数


x
舍入的值

☉  返回值



x的值四舍五入到最接近的整数(浮点值)。

☣  示例



/* round vs floor vs ceil vs trunc */
#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

🍄  另请参阅



floor 向下舍入(IEC 60559)function )
ceil 向上舍入(function )
trunc 去尾(function )
nearbyint 舍入到最近的整数值(function )
rint 舍入到整数值(function )


联系我们 免责声明 关于CandCplus 网站地图