函数
<cmath> <ctgmath>

nearbyint

     double nearbyint  (double x);      float nearbyintf (float x);long double nearbyintl (long double x);
     double nearbyint (double x);      float nearbyint (float x);long double nearbyint (long double x);     double nearbyint (T x);           // additional overloads for integral types
四舍五入到最接近的整数值
根据 fegetround 指定的舍入方向将 x 舍入到整数。

此函数不会引发 FE_INEXACT 异常。有关可能引发此异常的等效函数,请参阅 rint

头文件 <tgmath.h> 提供了此函数的类型通用宏版本。
在此头文件中(<cmath>)为 整数类型提供了其他重载:这些重载在计算之前有效地将 x 强制转换为 double(为 T 是任何整数类型定义)。

参数

x
要取整的值。

返回值

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

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* nearbyint example */
#include <stdio.h>      /* printf */
#include <fenv.h>       /* fegetround, FE_* */
#include <math.h>       /* nearbyint */

int main ()
{
  printf ("rounding using ");
  switch (fegetround()) {
    case FE_DOWNWARD: printf ("downward"); break;
    case FE_TONEAREST: printf ("to-nearest"); break;
    case FE_TOWARDZERO: printf ("toward-zero"); break;
    case FE_UPWARD: printf ("upward"); break;
    default: printf ("unknown");
  }
  printf (" rounding:\n");

  printf ( "nearbyint (2.3) = %.1f\n", nearbyint(2.3) );
  printf ( "nearbyint (3.8) = %.1f\n", nearbyint(3.8) );
  printf ( "nearbyint (-2.3) = %.1f\n", nearbyint(-2.3) );
  printf ( "nearbyint (-3.8) = %.1f\n", nearbyint(-3.8) );
  return 0;
}

可能的输出

Rounding using to-nearest rounding:
nearbyint (2.3) = 2.0
nearbyint (3.8) = 4.0
nearbyint (-2.3) = -2.0
nearbyint (-3.8) = -4.0


另见