2013-07-21 29 views
0

我有两个小数字,我希望找到百分比。查找红宝石中两个小数字的百分比

First number: 0.683789473684211 
Second number: 0.678958333333333 

我想知道数字的百分比是大还是小。这些数字很小,但可能会更大。第一个数字可能是250,第二个数字可能是0.3443435。我试图做的是检测第一个数字是否比第二个数字大25%。

我尝试使用这样的:

class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

但它不停地说我被零

,你会怎么做呢划分?

+0

在伪代码中:如果a>(b * 1.25)然后//做某事'做你需要的吗? – 2013-07-21 04:14:19

回答

0

你的代码的基本实现看起来对我来说是正确的。您能否提供产生该错误的具体示例和预期输出?

仅仅因为我很好奇,我把你的代码和一个小测试套件一起执行,并有3个通过测试。

require 'rubygems' 
require 'test/unit' 

class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.00 
    end 
end 

class PercentageTeset < Test::Unit::TestCase 
    def test_25_is_50_percent_of_50 
    assert_equal (25.percent_of(50)), 50.0 
    end 
    def test_50_is_100_percent_of_50 
    assert_equal (50.percent_of(50)), 100.0 
    end 
    def test_75_is_150_percent_of_50 
    assert_equal (75.percent_of(50)), 150.0 
    end 
end 
0
class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

p 0.683789473684211.percent_of(0.678958333333333) 

--output:-- 
100.71155181602376 

p 250.percent_of(0.3443435) 

--output:-- 
72601.9222084924 

p 0.000_001.percent_of(0.000_000_5) 

--output:-- 
200.0 

p 0.000_000_000_01.percent_of(0.000_000_000_01) 

--output:-- 
100.0 
0
class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

numbers = [ 0.683789473684211, 0.678958333333333 ] 
min_max = {min: numbers.min, max: numbers.max} 

puts "%<min>f is #{min_max[:min].percent_of(min_max[:max])} of %<max>f" % min_max 

这个方案有意见的,因为它显示的最小数量是最大数量的百分比,并显示数字。

如果您使用%d作为String#format方法,您将显示0。也许这就是你所说的,不确定。

编辑:使用minmax建议。

class Numeric 
    def percent_of(n) 
    self.to_f/n.to_f * 100.0 
    end 
end 

numbers = [ 0.683789473684211, 0.678958333333333 ] 
min_max = Hash.new 
min_max[:min], min_max[:max] = numbers.minmax 

puts "%<min>f is #{min_max[:min].percent_of(min_max[:max])} of %<max>f" % min_max 

我喜欢第一个版本,因为散列是根据需要构建的,而不是初始化和然后构建的。

+0

[minmax](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-minmax)是Enumerable中的现有方法。 – steenslag

1

为什么不直接拍你说你想做的事?

class Numeric 
    def sufficiently_bigger?(n, proportion = 1.25) 
    self >= proportion * n 
    end 
end 

p 5.sufficiently_bigger? 4   # => true 
p 5.sufficiently_bigger? 4.00001 # => false 

这将默认为大25%的检查,但你可以通过提供不同的值作为第二个参数覆盖比例。

如果您以产品形式表示比率而不是使用除法,它通常更容易并且避免需要明确的零分母检查。