负数的怪异Objective-C Mod行为 [英] Weird Objective-C Mod Behavior for Negative Numbers
本文介绍了负数的怪异Objective-C Mod行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我认为当修改后,负数应该放在正数空间中...我无法在objective-c中做到这一点
So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c
我希望这样:
-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
但是得到这个
-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
这是为什么,并且有解决方法?
Why is this and is there a workaround?
推荐答案
result = n % 3;
if( result < 0 ) result += 3;
不要按照其他答案中的建议执行额外的mod操作.它们非常昂贵且不必要.
Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.
这篇关于负数的怪异Objective-C Mod行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文