ホームC言語ヘッダファイル別一覧 | C言語アルファベット別一覧math.h ≫ nexttoward, nexttowardf, nexttowardl

The nexttoward functions (C99) - nexttoward, nexttowardf, nexttowardl

実軸上で x から見て y の方向にある x の次に表現可能な値を求めます.x と y が等しい場合は y をその関数の型に変換して返します.

nexttoward (C99)

#include <math.h>
double nexttoward(
    double x,
    long double y
);

nexttoward 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,double 型で返します.

nexttowardf (C99)

#include <math.h>
float nexttowardf(
    float x,
    long double y
);

nexttowardf 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,float 型で返します.

nexttowardl (C99)

#include <math.h>
long double nexttowardl(
    long double x,
    long double y
);

nexttowardl 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,long double 型で返します.

nexttoward,nexttowardf,nexttowardl 関数は,x がその型で表現できる最大の有限な値であり,かつその結果が無限大かその型で表現できない場合,値域エラー (range error) が発生する事があります.

よく似た関数に nextafternextafterfnextafterl 関数があります.

戻り値

  • y の方向にある x の次の値

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

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

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

/* main */
int main(void) {
    double x_posi = 5.0, x_nega = -5.0;
    long double y_posi = 6.0L, y_nega = -6.0L;
    double result;

    result = nexttoward(x_posi, y_posi);
    printf("nexttoward(%.1f, %.1Lf) = %.16f\n", x_posi, y_posi, result);

    result = nexttoward(x_nega, y_posi);
    printf("nexttoward(%.1f, %.1Lf) = %.16f\n", x_nega, y_posi, result);

    result = nexttoward(x_posi, y_nega);
    printf("nexttoward(%.1f, %.1Lf) = %.16f\n", x_posi, y_nega, result);

    result = nexttoward(x_nega, y_nega);
    printf("nexttoward(%.1f, %.1Lf) = %.16f\n", x_nega, y_nega, result);

    return EXIT_SUCCESS;
}

実行例

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

nexttoward(5.0, 6.0) = 5.0000000000000009
nexttoward(-5.0, 6.0) = -4.9999999999999991
nexttoward(5.0, -6.0) = 4.9999999999999991
nexttoward(-5.0, -6.0) = -5.0000000000000009

Cプログラマの必読書

たくさんあるC言語関連の書籍の中でも特に役に立った本です.よかったら参考にしてみてください.

C実践プログラミング 第3版

C言語の実践的参考書.少々値段は張りますが初心者を脱しようとしている人は絶対に読むべきです.
文法だけでなく,コーディングスタイルやデバッグなど文字通り「実践的」なことが書かれているので非常にためになります. オライリーの本は,読みにくい本が多いのですが本書はとても読みやすくオススメです.


C言語ポインタ完全制覇 (標準プログラマーズライブラリ)

ポインタの解説書としては最高の書籍です.
この1冊でポインタを完全に理解することができます.全くの初学者が読むには敷居が高いですが,入門書を読み終えた後に読むと非常に有益です.