如何在 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/