Ruby中数组的中值不浮动
好的,伙计们……我需要一些帮助来获取ruby中数组的中值 这是我的密码:Ruby中数组的中值不浮动,ruby,arrays,median,Ruby,Arrays,Median,好的,伙计们……我需要一些帮助来获取ruby中数组的中值 这是我的密码: def median(array) array.sort! # sort the array elements = array.count # count the elements in the array center = elements/2 # find the center of the array elements.even? ? (array[center] + array[center+1]
def median(array)
array.sort! # sort the array
elements = array.count # count the elements in the array
center = elements/2 # find the center of the array
elements.even? ? (array[center] + array[center+1])/2 : array[center] # if elements are even take both the center numbers of array and divide in half, if odd...get the center number
end
只是不确定在哪里应用.to\u f,因为它不会返回任何需要浮动的内容
谢谢我意识到您已经解决了自己的问题,但是这个版本更干净、更安全:
def median(array)
raise ArgumentError, 'Cannot find the median on an empty array' if array.size == 0
sorted = array.sort
midpoint, remainder = sorted.length.divmod(2)
if remainder == 0 # even count, average middle two
sorted[midpoint-1,2].inject(:+) / 2.0
else
sorted[midpoint]
end
end
你试过了吗
(array[center]。to_f+array[center+1]。to_f)/2:array[center]
无需使用to_f
,只需除以2.0
就可以了,需要所有人的帮助…谢谢。你不应该使用“center=(elements-1)/2”吗?由于数组是0索引的,如果元素等于2(例如,使用此数组[5,10]),则中心等于1(“中心=元素/2”)。“元素”为偶数时,中位数为“(数组[center]+数组[center+1])/2”,即“10+nil”,因为“center+1”将超出范围。此修复程序应与Yevgeniy Anfilofyev的修复程序一起使用。