forked from skywalkerjason/comp1110-exam-2022s2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQ1AverageInRange.java
48 lines (44 loc) · 1.56 KB
/
Q1AverageInRange.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package comp1110.exam;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class Q1AverageInRange {
/**
* Given an array of integers and a start and end value, return the
* the average of the array elements that are within the range from
* start to end, inclusive; that is, the average of all values v in
* the array such that start <= v <= end.
*
* Note that start and end are values, **not** array indices.
*
* For example:
*
* If the array contains {20,1,5,2,33}, start is 5 and end is 40, the
* average is (5 + 20 + 33) / 3 = 19.33333.
*
* If there are no values in the array that fall within the specified
* range, the average is undefined; in this case the method should
* return the end value.
*
* @param in an array of integers.
* @param start the start value of the range (inclusive).
* @param end the end value of the range (inclusive).
* @return the average of the elements with value between start to end,
* or end if the average is undefined (no values within range).
*/
public static double averageInRange(int[] in, int start, int end) {
int count = 0;
int sum=0;
for (int j : in) {
if (j >= start && j <= end) {
sum += j;
count++;
}
}
if (count==0){
return end;
}else {
return (double) sum/(double)count;
}
// FIXME
}
}