Weird Objective-C Mod Behavior for Negative Numbers

前端 未结 12 1931
旧巷少年郎
旧巷少年郎 2020-12-09 15:00

So I thought that negative numbers, when mod\'ed should be put into positive space... I cant get this to happen in objective-c

I expect this:

-1 % 3          


        
12条回答
  •  臣服心动
    2020-12-09 15:07

    result = n % 3;
    if( result < 0 ) result += 3;
    

    Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.

提交回复
热议问题