为什么Ruby中的除法返回整数而不是十进制值?

人气:444 发布:2022-10-16 标签: ruby math floating-point division integer-division

问题描述

For example:

9 / 5  #=> 1

but I expected 1.8. How can I get the correct decimal (non-integer) result? Why is it returning 1 at all?

解决方案

It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.8
9 / 5.0  #=> 1.8

791