带有浮点的模数c

时间:2012-06-14 16:41:51

标签: c floating-point integer floating-point-conversion

我在编译以下程序时非法使用浮点错误。请让我知道我犯了什么错误。

#include<stdio.h>
#include<conio.h>

void main()
{
    float a;
    clrscr();
    printf("\n Enter the num : ");
    scanf("%f", &a);

    if ( a >= 0 )
    {
        if ( (a % 2) == 0 ) //ERROR HERE
        {
            printf("\n You entered a positive even num");
        }
        else
        {
            printf("\n You entered a positive odd num");
        }
    }
    else
    {
        if ( (a % 2) == 0 ) //ERROR HERE
        {
            printf("\n You entered a negative even num");
        }
        else
        {
            printf("\n You entered a negative odd num");
        }
    }
    getch();
}

1 个答案:

答案 0 :(得分:5)

因为%适用于整数类型。使用fmod()

但像往常一样,要对performing equality comparisons (==) with floating-point types保持警惕。也许在你的情况下,最好使用整数类型。