The round functions (C99) - round, roundf, roundl

引数を最も近い整数値に丸めます.引数がちょうど中間にある場合は,その時点の丸め方向にかかわらず 0 から遠い方向を選びます.(四捨五入)

round (C99)

#include <math.h>
double round(
    double x
);

round 関数は x を最も近い整数値に丸め,結果を double 型で返します.引数がちょうど中間にある場合は,その時点の丸め方向にかかわらず 0 から遠い方向を選びます.

roundf (C99)

#include <math.h>
float roundf(
    float x
);

roundf 関数は x を最も近い整数値に丸め,結果を float 型で返します.引数がちょうど中間にある場合は,その時点の丸め方向にかかわらず 0 から遠い方向を選びます.

roundl (C99)

#include <math.h>
long double roundl(
    long double x
);

roundl 関数は x を最も近い整数値に丸め,結果を long double 型で返します.引数がちょうど中間にある場合は,その時点の丸め方向にかかわらず 0 から遠い方向を選びます.

戻り値

  • 丸めた整数値

C言語サンプルプログラム

以下に round 関数を使用したサンプルプログラムを示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* main */
int main(void) {
    double x1 = 5.0001, x2 = -5.0001;
    double x3 = 0.0;
    double x4 = 5.5000, x5 = -5.5000;
    double y1, y2, y3, y4, y5;

    y1 = round(x1);
    y2 = round(x2);
    y3 = round(x3);
    y4 = round(x4);
    y5 = round(x5);

    printf("round(%.4f) = %.4f\n", x1, y1);
    printf("round(%.4f) = %.4f\n", x2, y2);
    printf("round(%.4f) = %.4f\n", x3, y3);
    printf("round(%.4f) = %.4f\n", x4, y4);
    printf("round(%.4f) = %.4f\n", x5, y5);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラムの実行結果は以下のようになります.

round(5.0001) = 5.0000
round(-5.0001) = -5.0000
round(0.0000) = 0.0000
round(5.5000) = 6.0000
round(-5.5000) = -6.0000