Weird Objective-C Mod Behavior for Negative Numbers

前端 未结 12 1939
旧巷少年郎
旧巷少年郎 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:05

    UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:

    int result = (n + 3) % 3;
    

    Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.

提交回复
热议问题