我正在尝试使用Ruby来获得除法的剩余部分.
假设我们试图将208除以11.
决赛应该是"18剩余10"......我最终需要的是那个10.
这是我到目前为止所得到的,但它在这个用例中窒息(说剩下的是0).
division = 208.to_f / 11
rounded = (division*10).ceil/10.0
remainder = rounded.round(1).to_s.last.to_i
Run Code Online (Sandbox Code Playgroud)
Jos*_*Lee 72
模运算符:
> 208 % 11
=> 10
Run Code Online (Sandbox Code Playgroud)
Phr*_*ogz 50
如果只需要整数部分,请对/运算符或Numeric#div方法使用整数:
quotient = 208 / 11
#=> 18
quotient = 208.0.div 11
#=> 18
Run Code Online (Sandbox Code Playgroud)
如果只需要余数,请使用%运算符或Numeric#modulo方法:
modulus = 208 % 11
#=> 10
modulus = 208.0.modulo 11
#=> 10.0
Run Code Online (Sandbox Code Playgroud)
如果您需要两者,请使用该Numeric#divmod方法.如果接收器或参数是浮点数,这甚至可以工作:
quotient, modulus = 208.divmod(11)
#=> [18, 10]
208.0.divmod(11)
#=> [18, 10.0]
208.divmod(11.0)
#=> [18, 10.0]
Run Code Online (Sandbox Code Playgroud)
同样感兴趣的是该Numeric#remainder方法.所有这些之间的差异可以在文档中divmod看到.
小智 5
请使用Numeric#remainder因为 mod 不是余数
模数:
5.modulo(3)
#=> 2
5.modulo(-3)
#=> -1
Run Code Online (Sandbox Code Playgroud)
余:
5.remainder(3)
#=> 2
5.remainder(-3)
#=> 2
Run Code Online (Sandbox Code Playgroud)
这是讨论问题的链接 https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/