84

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?

2 Answers2

207

% 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.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • 2
    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. –  Aug 13 '09 at 10:31
  • Also what's the difference between tgmath.h and math.h anyway? – user4951 Nov 19 '12 at 14:17
  • 4
    Jim: `tgmath.h` is "type generic" (hence the "tg") and thus will decide which `math.h` function to call given the type of your input. (For instance, calling `floor(x)` with `tgmath.h` included will call (from `math.h`) `floorf(x)` if `x` is a `float`, `floor(x)` if `x` is a `double`, or `floorl(x)` if `x` is a `long double`.) – George WS Oct 04 '13 at 20:54
11

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
  • 5,812
  • 5
  • 26
  • 30
  • 3
    This, of course, will not give you the correct answer, because of rounding. – fishinear Dec 01 '16 at 18:11
  • this seems like a ridiculous answer, but it's often pretty close to what you need. Of course you'll get rounding but when you're dealing with CGSizes etc., this is totally fine. – Dan Rosenstark Apr 30 '21 at 01:00