18

have been searching for a mod operator in ios, just like the % in c, but no luck in finding it. Tried the answer in this link but it gives the same error. I have a float variable 'rotationAngle' whose angle keeps incrementing or decrementing based on the users finger movement. Some thing like this:

if (startPoint.x < pt.x) {
    if (pt.y<936/2) 
        rotationAngle += pt.x - startPoint.x;
    else
        rotationAngle += startPoint.x - pt.x;   
    }
    rotationAngle = (rotationAngle % 360);
}

I just need to make sure that the rotationAngle doesnot cross the +/- 360 limit. Any help any body. Thanks

Community
  • 1
  • 1
nuteron
  • 531
  • 2
  • 8
  • 26
  • 3
    Eh, Objective-C extends from C. Therefore C's `%` operator also works in Objective-C. **However** floats cannot do `%` so you need to make it an int first. – Tom van der Woerdt Apr 27 '12 at 13:15

3 Answers3

43

You can use fmod (for double) and fmodf (for float) of math.h:

#import <math.h>

rotationAngle = fmodf(rotationAngle, 360.0f);
Hailei
  • 42,163
  • 6
  • 44
  • 69
12

Use the fmod function, which does a floation-point modulo, for definition see here: http://www.cplusplus.com/reference/clibrary/cmath/fmod/. Examples of how it works (with the return values):

fmodf(100, 360); // 100
fmodf(300, 360); // 300
fmodf(500, 360); // 140
fmodf(1600, 360); // 160
fmodf(-100, 360); // -100
fmodf(-300, 360); // -300
fmodf(-500, 360); // -140

fmodf takes "float" as arguments, fmod takes "double" and fmodl takes "double long", but they all do the same thing.

kuba
  • 7,329
  • 1
  • 36
  • 41
  • Thanks for your answer this works, objective c is so diverse, once you call a method like [self methodName:parameters], next line you call a method like methodName(parameters).. – nuteron Jun 07 '12 at 05:57
1

I cast it to an int first

rotationAngle = (((int)rotationAngle) % 360);

if you want more accuracy use

float t = rotationAngle-((int)rotationAngle);
rotationAngle = (((int)rotationAngle) % 360);
rotationAngle+=t;
Jason McTaggart
  • 878
  • 1
  • 7
  • 18
  • I don't think its enough to worry about unless you are using it to enter a direction of travel for a spaceship. If it loses any at all witch I don't think it will, there is no rounding, casting, or devision so it won't. – Jason McTaggart Apr 27 '12 at 14:03