Weird Objective-C Mod Behavior for Negative Numbers

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

    Instead of a%b

    Use: a-b*floor((float)a/(float)b)

    You're expecting remainder and are using modulo. In math they are the same thing, in C they are different. GNU-C has Rem() and Mod(), objective-c only has mod() so you will have to use the code above to simulate rem function (which is the same as mod in the math world, but not in the programming world [for most languages at least])


    Also note you could define an easy to use macro for this.

    #define rem(a,b) ((int)(a-b*floor((float)a/(float)b)))

    Then you could just use rem(-1,3) in your code and it should work fine.

提交回复
热议问题