How do you do modulo or remainder in Erlang?

后端 未结 8 1812
悲哀的现实
悲哀的现实 2020-12-29 17:56

I\'m brand new to Erlang. How do you do modulo (get the remainder of a division)? It\'s % in most C-like languages, but that designates a comment in Erlang.

Several

8条回答
  •  长发绾君心
    2020-12-29 18:35

    In Erlang, 5 rem 3. gives 2, and -5 rem 3. gives -2. If I understand your question, you would want -5 rem 3. to give 1 instead, since -5 = -2 * 3 + 1.

    Does this do what you want?

    mod(X,Y) when X > 0 -> X rem Y;
    mod(X,Y) when X < 0 -> Y + X rem Y;
    mod(0,Y) -> 0.
    

提交回复
热议问题