4

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)

mjs
  • 2,837
  • 4
  • 28
  • 48
  • 2
    Answer is already there. For some more question like _Why not working on float_? please have a look on [why-does-modulus-division-only-work-with-integers?](http://stackoverflow.com/questions/6102948/why-does-modulus-division-only-work-with-integers) – Dayal rai Oct 11 '13 at 11:45
  • 3
    To round up if there is **any** non-zero fraction part, use `ceilf`, not `roundf`. Note: `ceilf` rounds toward infinity; if you want negative numbers rounded toward —infinity (e.g., —3.25 to —4), you will need additional code. – Eric Postpischil Oct 11 '13 at 11:50
  • @EricPostpischil thats almost exactly what I want. I dont have it on my target though, so i guess its the double version `ceil` for me... – mjs Oct 11 '13 at 12:28
  • 2
    Look in your C manual under `%`. It will say what the valid operands are. See if `float` is listed as a valid operand. (Spoiler alert: It's not.) – Raymond Chen Oct 11 '13 at 13:45

3 Answers3

20

% 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
{
    ...
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
3

The modulus operator only works on integers. For floating point values use fmod or fmodf.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

% this only works with integers use fmod for floating point or double values**

double fmod(double x, double y)


x -- This is the floating point value with the division numerator i.e. x.

y -- This is the floating point value with the division denominator i.e. y.
Sohil Omer
  • 1,171
  • 7
  • 14