The lround functions (C99) - lround, lroundf, lroundl

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

lround (C99)

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

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

lroundf (C99)

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

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

lroundl (C99)

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

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

lround,lroundf,lroundl 関数が丸めた値が返却値の型の範囲外になった場合の結果は未規定です.また,x の絶対値が大きすぎる場合には値域エラー (range error) が発生することがあります.

戻り値

  • 丸めた整数値

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

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

/* 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;
    long y1, y2, y3, y4, y5;

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

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

    return EXIT_SUCCESS;
}

実行例

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

lround(5.0001) = 5
lround(-5.0001) = -5
lround(0.0000) = 0
lround(5.5000) = 6
lround(-5.5000) = -6