Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: invalid operands to binary % when taking modulus of float [duplicate]

Tags:

c

Its been a fairly long week, so forgive me if I am being thick.

I have some code like:

float someFloat = 0;
//....do some stuff to someFloat
//....

if( someFloat % 1)
{
   //take some action
}

I get a compiler error : error: invalid operands to binary %

Assuming the compiler isnt on drugs, whats wrong with this?

EDIT: As an aside, what I actually wanted to do was detect non-integer value and round up. What I should have been doing was calling roundf (and I guess checking if the return is less than the operand and then incrementing if so, to take care that we have rounded up)

like image 739
mjs Avatar asked Nov 28 '22 15:11

mjs


1 Answers

% is an integer operator - use fmod or fmodf for doubles or floats.

Alternatively if you expect your float to represent integer values then convert it to an int first, e.g.:

if ((int)someFloat % 2 == 1) // if f is an odd integer value
{
    ...
}
like image 142
Paul R Avatar answered Dec 21 '22 11:12

Paul R