Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions Maths/Average.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
* Calculate average of a list of numbers
*/
public class Average {
private static final double SMALL_VALUE = 0.00001f;
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;
assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE;
assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE;
assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE;
int[] array = {2, 4, 10};
assert average(array) == 5;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

 assert average(new int[]{2, 4, 10}) == 5;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is also ok

}

/**
Expand All @@ -23,4 +26,19 @@ public static double average(double[] numbers) {
}
return sum / numbers.length;
}
}

/**
* find average value of int array
*
* @param array the array contains element and the sum does not
* excess long value limit
* @return average value
*/
public static int average(int[] array) {
long sum = 0;
for (int i = 0 ; i < array.length; ++i) {
sum += array[i];
}
return (int)(sum / array.length);
}
}