实数上的红宝石力整数除法

xxj*_*jnn 2 ruby math

红宝石如何强制整数除以实数?

# 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]
Run Code Online (Sandbox Code Playgroud)

我想要[ 3.0, 1.1 ].假设这不能在香草红宝石中完成并且需要使用宝石?

Ale*_*kin 6

Numeric#divmod 来救援:

7.1.divmod 2
#? [
#  [0] 3,
#  [1] 1.0999999999999996
# ]
Run Code Online (Sandbox Code Playgroud)

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

7.1.div 2
#? 3
Run Code Online (Sandbox Code Playgroud)

  • 或者`7.1.div(2)`仅适用于商部分. (2认同)