# A ruby program for finding average mean
module AverageMean
# Average mean = sum of elements / total number of elements
def self.average_mean(n, *array)
if n.instance_of? Integer
if n == array.size
puts "The average mean of the following elements #{array} is #{array.sum / array.size}."
else
puts "Provide the required #{n} elements properly!"
end
else
raise
end
rescue StandardError
puts 'Error: Please provide number only!'
end
end
# Valid inputs
AverageMean.average_mean(2, 3, 1)
AverageMean.average_mean(5, 1, 2, 3, 4, 5)
AverageMean.average_mean(3, 2, 2, 2)
# Invalid inputs
AverageMean.average_mean(2, 3, 1, 5)
AverageMean.average_mean(2, 3, 'a')
AverageMean.average_mean('a', 1, 2)
Calculate the average of a list of numbers using mean.
Calculating the mean of a list of numbers is one of the most common ways to determine the average of those numbers.
Calculating a mean would be useful in these situations:
Given the list [2, 4, 6, 8, 20, 50, 70]
, let's calculate the average.
Send [2, 4, 6, 8, 20, 50, 70]
as input for a method/function.
Add all the numbers together.
2 + 4 + 6 + 8 + 20 + 50 + 70 = 160
, so sum = 160
.
Count the numbers in the list.
The list has seven numbers, so count = 7
.
Divide the sum of all the numbers by the count of the numbers.
sum = 160
count = 7
If we ignore significant digits: sum / count =
22.857142
If we properly consider significant digits: sum / count = 23
Return the value of 22.857142 or 23
.