2013-07-21 7 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) then then something something '이 필요합니까? –

답변

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 

이 프로그램은 의견이 있습니다.

String#format 메서드에 %d을 사용하면 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 % 큰 수표이지만, 두 번째 인수와 다른 값을 제공하여 비례 성을 재정의 할 수 있습니다.

일반적으로 나누기보다는 제품 형식으로 비율을 표현하는 것이 더 쉽고 명시적인 제로 - 분모 수표가 필요 없습니다.