[BaekJoon] #1546 - 평균 [Java][C++]
[BaekJoon] #1546 - 평균 [Java][C++]
1. 아이디어
주어진 성적들을 배열로 받은 후 최댓값 $M$을 구한다. 이후 각 성적 $x$를 $x / M \times 100$으로 조작한 후 평균을 구하면 된다. 이때 정수 타입은 나머지가 버림 처리될 수 있음에 주의해야 한다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][C++]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
int max = 0;
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
max = Math.max(max, arr[i]);
}
double sum = 0;
for (int x : arr) {
sum += (double) x / max * 100;
}
System.out.println(sum / n);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
int mx = *max_element(v.begin(), v.end());
double sum = 0;
for (int x : v) {
sum += (double)x / mx * 100;
}
cout << sum / n;
}
This post is licensed under CC BY 4.0 by the author.