반응형
문제
풀이
- 먼저, 평균 값이 얼마인지 구해야함. 평균 값은 소수점으로 나올 수 있으므로 Double 자료형으로 입력을 받아준다.
- 평균 값이 얼마인지 구했다면, 평균을 넘는 학생의 수를 구해준다.
- 고차함수 filter를 사용해서 쉽게 구할 수 있음
- 평균을 넘는 학생의 수 / 총 학생의 수 * 100이 평균을 넘는 학생들의 비율
- 소수점 셋째 자리까지 출력해야 하므로, String(format::)을 사용해서 셋째 자리까지만 출력되도록 구현하면 끝!
- Foundation을 import 해야 사용할 수 있음
소스코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func solution() { | |
let input = readLine()!.split(separator: " ").map { Double($0)! } | |
let n = input.first! | |
let average = input[1...].reduce(0, +) / n | |
let answer = Double(input[1...].filter { $0 > average }.count) / n * 100 | |
print(String(format: "%.3f", answer) + "%") | |
} | |
let c = Int(readLine()!)! | |
(1...c).forEach { _ in solution() } |
후기
- String(format::)에 대해 몰랐다면 풀기에 조금 불편했을 것 같다.
- 처음에는 round 메서드를 사용해서 소수점 셋째짜리를 반올림해주고 풀었는데 String(format::)이 반올림도 지원하는 것을 알았다.
반응형
'PS > 백준' 카테고리의 다른 글
[BOJ] 백준 1065 한수 (Swift) (0) | 2022.12.30 |
---|---|
[BOJ] 백준 4673 셀프 넘버 (Swift) (0) | 2022.12.30 |
[BOJ] 백준 8958 OX퀴즈 (Swift) (1) | 2022.12.28 |
[BOJ] 백준 1546 평균 (Swift) (0) | 2022.12.27 |
[BOJ] 백준 3052 나머지 (Swift) (0) | 2022.12.27 |