Mod operator in ios
Solution 1
You can use fmod
(for double
) and fmodf
(for float
) of math.h:
#import <math.h>
rotationAngle = fmodf(rotationAngle, 360.0f);
Solution 2
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.
Solution 3
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;
Related videos on Youtube
nuteron
Am a beginner ios developer, developing mainly for the ipad.
Updated on July 09, 2022Comments
-
nuteron almost 2 years
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
-
Tom van der Woerdt almost 12 yearsEh, 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.
-
-
Jason McTaggart almost 12 yearsI 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.
-
nuteron almost 12 yearsThank u but its working without importing math.h also, very short and precise.
-
nuteron almost 12 yearsThanks 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)..