计算数字平均值

2015-01-28 0 362
计算数字平均值
# Gets the Average of a list of numbers.
def Average(array)
  # Placeholder for our answer
  answer = 0
  # Placeholder for our sum
  sum = 0
  # Get the length of the items in the array
  length = array.length
  # Loop through each number in our array
  array.each do |number|
    # Add each number to our current sum
    sum = sum + number.to_i
    # Exit the loop
  end
  # Get the average
  answer = (sum / length)
  # Return the answer
  return (sum / length)
  # Exit the method
end

# Gets the Average of a list of numbers.
def Average2(string)
  # Placeholder for our answer
  answer = 0
  # Placeholder for our sum
  sum = 0
  # Create an array from our list of numbers
  array = string.split(',')
  # Get the length of the items in the array
  length = array.length
  # Loop through each number in our array
  array.each do |number|
    # Add each number to our current sum
    sum = sum + number.to_i
    # Exit the loop
  end
  # Get the average
  answer = (sum / length)
  # Return the answer
  return (sum / length)
  # Exit the method
end

遇见资源网 ruby 计算数字平均值 http://www.ox520.com/16261.html

常见问题

相关文章

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

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