將浮點值四捨五入至最接近的整數值。
語法
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 later
參數
x
要四捨五入的浮點值。
傳回值
round 函式會傳回表示 x 的最接近整數的浮點值。 不論浮點進位模式設定為何,中間值都會背離零四捨五入。 不會傳回錯誤。
| 輸入 | SEH 例外狀況 | _matherr 例外 |
|---|---|---|
| ± QNaN,IND | none | _DOMAIN |
備註
因為 C++ 允許多載,所以您可以呼叫採用並傳回 round 和 float 值的 long double 的多載。 在 C 程式中,除非您使用 <tgmath.h> 巨集來呼叫此函式, round 否則一律會採用並傳 double回 。
如果您使用 中的round<tgmath.h>巨集,自變數的類型會決定選取哪一個函式版本。 如需詳細資料,請參閱型別泛型數學。
根據預設,此函式的全域狀態會限定於應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。
需求
| 常式 | 必要的標頭 |
|---|---|
round、 、 roundfroundl |
<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
另請參閱
數學與浮點支援
ceil、 、 ceilfceill
floor、 、 floorffloorl
fmod, fmodf
lrint、、lrintflrintl、llrint、、llrintf、llrintl
lround、、lroundflroundl、llround、、llroundf、llroundl
nearbyint、 、 nearbyintfnearbyintl
rint、 、 rintfrintl