Ruby 拒绝正确划分 [英] Ruby Refuses to Divide Correctly

查看:35
本文介绍了Ruby 拒绝正确划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想得到一个百分比.

I'm simply trying to get a percentage.

irb(main):001:0> (25 / 50) * 100
=> 0

这应该绝对等于 50,正如我的计算器所证实的(复制并粘贴相同的方程到 gcalc).为什么 Ruby 拒绝这样做?

This should most definitely equal 50, as confirmed by my calculator (copied and pasted the same equation into gcalc). Why does Ruby refuse to do this?

推荐答案

它正在做整数除法.

基本上,25 是一个整数(整数),50 也是,所以当你除以另一个时,它会得到另一个整数.

Basically, 25 is an integer (a whole number) and so is 50, so when you divide one by the other, it gives you another integer.

25 / 50 * 100 = 0.5 * 100 = 0 * 100 = 0

最好的方法是先乘,然后除.

The better way to do it is to first multiply, then divide.

25 * 100 / 50 = 2500 / 50 = 50

您还可以通过指定小数点来显式使用浮点运算,如下所示:

You can also use floating point arithmetic explicitly by specifying a decimal point as in:

25.0 / 50.0 * 100 = 0.5 * 100 = 50

这篇关于Ruby 拒绝正确划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆