From 3e169010fe7f4e38e420cfa4f6b6312aa9e64200 Mon Sep 17 00:00:00 2001 From: shellhub Date: Sun, 16 Aug 2020 13:58:14 +0800 Subject: [PATCH] add average --- Maths/Average.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Maths/Average.java diff --git a/Maths/Average.java b/Maths/Average.java new file mode 100644 index 00000000..35812ecc --- /dev/null +++ b/Maths/Average.java @@ -0,0 +1,26 @@ +package Maths; + +/** + * Calculate average of a list of numbers + */ +public class Average { + public static void main(String[] args) { + assert average(new double[]{3, 6, 9, 12, 15, 18, 21}) == 12; + assert average(new double[]{5, 10, 15, 20, 25, 30, 35}) == 20; + assert average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) == 4.5; + } + + /** + * Calculate average of a list of numbers + * + * @param numbers array to store numbers + * @return mean of given numbers + */ + public static double average(double[] numbers) { + double sum = 0; + for (double number : numbers) { + sum += number; + } + return sum / numbers.length; + } +}