C言語: 浮動小数点数が整数か判定する方法

C言語では、math.hヘッダファイルの関数を使用して、浮動小数点数が整数であるかどうかを判別することができます。以下は、例としてのコードです:

#include <stdio.h>
#include <math.h>

int is_integer(float num) {
    return num == floor(num);
}

int main() {
    float num = 3.0;

    if(is_integer(num)) {
        printf("The number is an integer.\n");
    } else {
        printf("The number is not an integer.\n");
    }

    return 0;
}

指定されたコード内で、is_integer関数はfloor関数を使用して浮動小数点数を整数に変換し、元の浮動小数点数と比較します。等しい場合は、その浮動小数点数が整数であると判断されます。

bannerAds