44 * Calculate average of a list of numbers
55 */
66public class Average {
7+ private static final double SMALL_VALUE = 0.00001f ;
78 public static void main (String [] args ) {
8- assert average (new double []{3 , 6 , 9 , 12 , 15 , 18 , 21 }) == 12 ;
9- assert average (new double []{5 , 10 , 15 , 20 , 25 , 30 , 35 }) == 20 ;
10- assert average (new double []{1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }) == 4.5 ;
9+ assert Math .abs (average (new double []{3 , 6 , 9 , 12 , 15 , 18 , 21 }) - 12 ) < SMALL_VALUE ;
10+ assert Math .abs (average (new double []{5 , 10 , 15 , 20 , 25 , 30 , 35 }) - 20 ) < SMALL_VALUE ;
11+ assert Math .abs (average (new double []{1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }) - 4.5 ) < SMALL_VALUE ;
12+ int [] array = {2 , 4 , 10 };
13+ assert average (array ) == 5 ;
1114 }
1215
1316 /**
@@ -23,4 +26,19 @@ public static double average(double[] numbers) {
2326 }
2427 return sum / numbers .length ;
2528 }
26- }
29+
30+ /**
31+ * find average value of int array
32+ *
33+ * @param array the array contains element and the sum does not
34+ * excess long value limit
35+ * @return average value
36+ */
37+ public static int average (int [] array ) {
38+ long sum = 0 ;
39+ for (int i = 0 ; i < array .length ; ++i ) {
40+ sum += array [i ];
41+ }
42+ return (int )(sum / array .length );
43+ }
44+ }
0 commit comments