ruby 强制对实数进行整数除法

标签 ruby math

如何在 ruby​​ 中强制对实数进行整数除法?

# integer division with integers - no problem
>> [ 7/2 , 7%2 ]
=> [3, 1]

# integer division with floats - '%' gives the remainder just fine...
# ...but for the quotient it used real division
>> [ 7.0/2 , 7.0%2 ]
=> [3.5, 1.0]

# This is what happens with non integer-y floats
>> [ 7.1/2 , 7.1%2 ]
=> [3.55, 1.0999999999999996]

我想要 [ 3.0, 1.1 ]。假设这不能在 vanilla ruby​​ 中完成并且需要使用 gem?

最佳答案

Numeric#divmod来救援:

7.1.divmod 2
#⇒ [
#  [0] 3,
#  [1] 1.0999999999999996
# ]

或者,仅对于商部分(归功于@Stefan):

7.1.div 2
#⇒ 3

关于ruby 强制对实数进行整数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42411559/

相关文章:

ruby - 如何在 Eclipse 的 ruby​​ 插件中自定义编辑器的背景颜色?

ruby-on-rails - render @users 和 render 'new' 有何不同?

javascript - 在 Javascript 函数中使用 onclick 函数拉取部分 (Ruby on Rails)

math - 这是在 python 中查找 sigmoid 函数的导数的正确方法吗?

python - 为什么在斯坦福的 cs231n SVM 中点积倒退?

ruby - 有没有办法使用! .include 中的运算符?方法?

python - 加号不携带

algorithm - 找到反向算法回到初始值

mysql - 按邮政编码公式计算的距离

ruby - 将 stderr 重定向到 Logger 实例