在Erlang你怎么做模或余数? [英] How do you do modulo or remainder in Erlang?

查看:166
本文介绍了在Erlang你怎么做模或余数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Erlang的全新品牌。你如何做模数(得到一个部门的剩余部分)?在大多数C语言中,它的百分比是%,但在Erlang中指定了一个注释。



几个人用rem回答,在大多数情况下都是正确的。但是我正在重新考虑这一点,因为现在我需要使用负数,而rem给你一个除数的余数,这与负数的模数不一样。

解决方案

在Erlang中,5 rem 3.给出2和-5 rem 3.给出-2。如果我明白你的问题,你会想要-5 rem 3.给予1,因为-5 = -2 * 3 + 1。



这样做你做什么想要?

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


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 people answered with rem, which in most cases is fine. But I'm revisiting this because now I need to use negative numbers and rem gives you the remainder of a division, which is not the same as modulo for negative numbers.

解决方案

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.

这篇关于在Erlang你怎么做模或余数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆