round, roundf, roundl

将浮点值舍入为最接近的整数值。

语法

double round(
   double x
);
float round(
   float x
);  // C++ only
long double round(
   long double x
);  // C++ only
float roundf(
   float x
);
long double roundl(
   long double x
);
#define round(X) // Requires C11 or higher

参数

x
要舍入的浮点值。

返回值

round 函数将返回表示最接近 x 的整数的浮点值。 中间值从零舍入,这与浮点舍入模式的设置无关。 无错误返回。

输入 SEH 异常 _matherr 异常
± QNaN、IND _DOMAIN

注解

由于 C++ 允许重载,因此你可以调用采用并返回 roundfloat 值的 long double 重载。 在 C 程序中,除非你使用 <tgmath.h> 宏来调用此函数,否则 round 始终采用并返回 double

如果使用 <tgmath.h> 中的 round 宏,参数的类型将确定选择哪个版本的函数。 有关详细信息,请参阅泛型类型数学

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

要求

例程 必需的标头
round, roundf, roundl <math.h>
round <tgmath.h>

有关兼容性的详细信息,请参阅 兼容性

示例

// Build with: cl /W3 /Tc
// This example displays the rounded
// results of floating-point values

#include <math.h>
#include <stdio.h>

int main()
{
    printf("===== Round a float\n\n");
    float floatValue = 2.4999999f; // float stores a value close to, but not exactly equal to, the initializer below. floatValue will contain 2.5 because it is the closest single precision value
    printf("roundf(%.1000g) is %.1000g\n", floatValue, roundf(floatValue));
    printf("roundf(%.1000g) is %.1000g\n", -floatValue, roundf(-floatValue));

    // double stores a value close to, but not exactly equal to, the initializer below. The closest double value is just slightly larger.
    double doubleValue = 2.4999999;
    printf("\n===== Round a double\n\n");
    printf("round(%.1000g) is %.1000g\n", doubleValue, round(doubleValue));
    printf("round(%.1000g) is %.1000g\n", -doubleValue, round(-doubleValue));

    // long double stores a value close to, but not exactly equal to, the initializer below. The closest long double value is just slightly larger.
    long double longDoubleValue = 2.4999999L;
    printf("\n===== Round a long double\n\n");
    printf("roundl(%.1000g) is %.1000g\n", longDoubleValue, roundl(longDoubleValue));
    printf("roundl(%.1000g) is %.1000g\n", -longDoubleValue, roundl(-longDoubleValue));

    return 0;
}
===== Round a float

roundf(2.5) is 3
roundf(-2.5) is -3

===== Round a double

round(2.499999900000000163657887242152355611324310302734375) is 2
round(-2.499999900000000163657887242152355611324310302734375) is -2

===== Round a long double

roundl(2.499999900000000163657887242152355611324310302734375) is 2
roundl(-2.499999900000000163657887242152355611324310302734375) is -2

另请参阅

数学和浮点支持
ceilceilfceill
floorfloorffloorl
fmodfmodf
lrintlrintflrintlllrintllrintfllrintl
lroundlroundflroundlllroundllroundfllroundl
nearbyintnearbyintfnearbyintl
rintrintfrintl