平均数/中间数 mean/median

2015-08-10 0 446
平均数/中间数 mean/median
class Array 
    def mean 
        inject(0) {|sum, x| sum += x} / size.to_f
    end
    def median 
        sorted = self.sort() 
        if (sorted.size.modulo(2) == 0) then 
            ((sorted[(sorted.size/2)-1]+sorted[(sorted.size/2)])/2.0) 
        else 
            sorted[sorted.size/2] 
        end 
    end 
    def mode 
        occures = Hash.new(0) 
        self.each{|x| occures[x] += 1 } 
        max = 0 
        modes = [] 
        occures.each{|key, value| 
            if value > max then 
                modes = [key] 
                max = value 
            elsif value == max 
                modes.push(key) 
            end 
        } 
        modes 
    end 
end 

num_list = [92,86,79,64,89,92,88,62,58,95,100,97] 
puts "Mean: #{num_list.mean}" 
puts "Median: #{num_list.median}" 
puts "Mode: #{num_list.mode}"

遇见资源网 ruby 平均数/中间数 mean/median http://www.ox520.com/16427.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务