tags:

views:

2121

answers:

3

I have two CGFloat values, and want to calculate the modulo result. Or in other words: I want to know what's left if valueA is placed as much as possible into valueB.

So I just tried:

CGFloat moduloResult = valueB % valueA;

the compiler complains about the % and tells me: "invalid operands to binary %". Any idea?

+7  A: 

% is for int or long, not float or double.

You can use fmod() or fmodf() from <math.h> instead.

Better is <tgmath.h> as suggested by the inventor of CGFloat.

mouviciel
is tgmath.h available on the iphone? I wonder because I never had to include math.h. It comes with the foundation framework, I think.
HelloMoon
+1  A: 

If I remember correctly modulo requires 2 ints as its input so you'd need something like:

CGFloat moduloResult = (float)((int)valueB % (int)valueA);

Assuming that valueB and valueA are both floats

James Raybould
+1  A: 

The % operator doesn't work on floating-point values. You'll have to use a function to calculate what you want. Here's the basic pseudocode of what it would look like:

B % A = B - (floor(B / A) * A)

There are also library functions which will do this for you in math.h or tgmath.h

Amber