ios ios中的Mod操作符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10351293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:08:03  来源:igfitidea点击:

Mod operator in ios

iosiphoneobjective-ccmodulo

提问by nuteron

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 linkbut 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:

一直在 ios 中寻找 mod 运算符,就像%在 c 中一样,但没有找到它。尝试了此链接中的答案,但它给出了相同的错误。我有一个浮动变量“rotationAngle”,它的角度会根据用户手指的移动不断增加或减少。像这样的事情:

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

我只需要确保rotationAngle 不超过+/- 360 的限制。任何帮助任何身体。谢谢

回答by Hailei

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

您可以使用math.h 的fmod(for double) 和fmodf(for float):

#import <math.h>

rotationAngle = fmodf(rotationAngle, 360.0f);

回答by kuba

Use the fmodfunction, 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):

使用执行fmod浮点模数的函数,定义见这里:http: //www.cplusplus.com/reference/clibrary/cmath/fmod/。它是如何工作的示例(带有返回值):

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

fmodftakes "float" as arguments, fmodtakes "double" and fmodltakes "double long", but they all do the same thing.

fmodf将“float”作为参数,fmod采用“double”和fmodl“double long”,但它们都做同样的事情。

回答by Jason McTaggart

I cast it to an int first

我首先将它转换为 int

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

if you want more accuracy use

如果你想要更准确的使用

float t = rotationAngle-((int)rotationAngle);
rotationAngle = (((int)rotationAngle) % 360);
rotationAngle+=t;