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++ ではオーバーロードが可能であるため、 round および float の値を受け取って返す long double のオーバーロードを呼び出すことができます。 C プログラムでは、<tgmath.h> マクロを使用してこの関数を呼び出す場合を除き、round では常に double を受け取って返します。

マクロを<tgmath.h>使用するround場合は、引数の型によって、どのバージョンの関数が選択されているかが決まります。 詳細については、「ジェネリック型数値演算」を参照してください。

既定では、この関数のグローバル状態の適用対象は、アプリケーションになります。 この動作を変更するには、「CRT のグローバル状態」を参照してください

必要条件

ルーチンによって返される値 必須ヘッダー
round, roundf, roundl <math.h>
round マクロ <tgmath.h>

互換性の詳細については、「 Compatibility」を参照してください。

// 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, ceilf, ceill
floor, floorf, floorl
fmod, fmodf
lrint, lrintf, lrintl, llrint, llrintf, llrintl
lround, lroundf, lroundl, llround, llroundf, llroundl
nearbyint, nearbyintf, nearbyintl
rint, rintf, rintl