[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
public static void main(String[] args) {
    int[] A = new int[]{5, 2, 6, 4}; 
    int[] B = new int[]{-4, 0, 2, -4};
	
    System.out.println("average : "+average(A));
    System.out.println("average : "+average(B));
    
    System.out.println("average : "+averageUseStream(A));
    System.out.println("average : "+averageUseStream(B));
}

public static double average(int[] arr) {
    double result = 0;
    
    for (int x=0; x<arr.length; x++) {
        int num = arr[x];
        result += num;
    }
    result = result / arr.length;
    
    return result;
}

public static double averageUseStream(int[] arr) {
	return Arrays.stream(arr).average().getAsDouble();
}


Tags:

Updated:

Leave a comment