rippy
rippy

Reputation: 195

Modulus with floating point in c

I'm getting illegal use of floating point error on compiling the following program. Please let me know where I am committing a mistake.

#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();
}

Upvotes: 0

Views: 314

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Because % is for integer types. Use fmod().

But as usual, be very wary of performing equality comparisons (==) with floating-point types. Perhaps in your case it would be better to work with integer types throughout.

Upvotes: 5

Related Questions