ruby 如何在Ruby中找到除法的余数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9086131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:43:45  来源:igfitidea点击:

How to find remainder of a division in Ruby?

rubymath

提问by Shpigford

I'm trying to get the remainder of a division using Ruby.

我正在尝试使用 Ruby 获取除法的其余部分。

Let's say we're trying to divide 208 by 11.

假设我们试图将 208 除以 11。

The final should be "18 with a remainder of 10"...what I ultimately need is that 10.

决赛应该是“18 余 10”...我最终需要的是10.

Here's what I've got so far, but it chokes in this use case (saying the remainder is 0).

这是我到目前为止所得到的,但在这个用例中它令人窒息(说其余的是0)。

division = 208.to_f / 11
rounded = (division*10).ceil/10.0
remainder = rounded.round(1).to_s.last.to_i

回答by Josh Lee

The modulo operator:

模运算符:

> 208 % 11
=> 10

回答by Phrogz

If you need just the integer portion, use integers with the /operator, or the Numeric#divmethod:

如果您只需要整数部分,请将整数与/运算符或Numeric#div方法一起使用:

quotient = 208 / 11
#=> 18

quotient = 208.0.div 11
#=> 18

If you need just the remainder, use the %operator or the Numeric#modulomethod:

如果您只需要余数,请使用%运算符或Numeric#modulo方法:

modulus = 208 % 11
#=> 10

modulus = 208.0.modulo 11
#=> 10.0

If you need both, use the Numeric#divmodmethod. This even works if either the receiver or argument is a float:

如果两者都需要,请使用该Numeric#divmod方法。如果接收者或参数是浮点数,这甚至有效:

quotient, modulus = 208.divmod(11)
#=> [18, 10]

208.0.divmod(11)
#=> [18, 10.0]

208.divmod(11.0)
#=> [18, 10.0]

Also of interest is the Numeric#remaindermethod. The differences between all of these can be seen in the documentation for divmod.

同样令人感兴趣的是Numeric#remainder方法。所有这些之间的差异可以在可见的文档divmod

回答by xinr

please use Numeric#remainderbecause mod is not remainder

请使用Numeric#remainder因为 mod 不是余数

Modulo:

模数:

5.modulo(3)
#=> 2
5.modulo(-3)
#=> -1

Remainder:

余:

5.remainder(3)
#=> 2
5.remainder(-3)
#=> 2

here is the link discussing the problem https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/

这是讨论问题的链接 https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/