Weird Objective-C Mod Behavior for Negative Numbers

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

    We have a problem of language:

    math-er-says: i take this number plus that number mod other-number
    code-er-hears: I add two numbers and then devide the result by other-number
    code-er-says: what about negative numbers?
    math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers?
    code-er-says: field what? ...
    
    • the math person in this conversations is talking about doing math in a circular number line. If you subtract off the bottom you wrap around to the top.
    • the code person is talking about an operator that calculates remainder.

    In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.

提交回复
热议问题