带有浮点的模数c

rip*_*ppy 0 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();
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 5

因为%是整数类型.使用fmod().

但是像往常一样,要非常谨慎地使用浮点类型执行相等比较(==).也许在你的情况下,最好使用整数类型.

  • ...或者更好地将`a`改为`int`(如果你推理奇数/偶数,你或许可以使用整数). (3认同)