문제:
https://www.acmicpc.net/problem/4344
4344번: 평균은 넘겠지
대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.
www.acmicpc.net
코드:
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // 테스트케이스 개수
double [] result = new double[num]; // 결과
for(int i=0;i<num;i++) {
int stuNum = sc.nextInt(); // 학생 수
int total = 0; // 총 점수
int count = 0; // 평균을 넘은 사람 수
int [] testCase = new int[stuNum]; // 학생 각 점수
for(int j=0;j<stuNum;j++) {
testCase[j] = sc.nextInt();
total += testCase[j]; // 각 점수 입력 후 더함
}
int ave = total/stuNum; // 평균 점수
for(int k=0;k<stuNum;k++) {
if(ave < testCase[k]) {
count++; // 평균 넘는 사람 수 세기
}
}
result[i] = (double)count/stuNum*100; // 비율
}
for(int l=0;l<num;l++) {
System.out.println(String.format("%.3f", Math.round(result[l]*1000)/1000d)+"%");
}
}
}
for(int l=0;l<num;l++) {
System.out.println(String.format("%.3f", Math.round(result[l]*1000)/1000d)+"%");
}
이 코드의 핵심이 되는 부분은 마지막 for 문이다.
Math.round를 통해 반올림하여 출력하게 된다면 첫 번째 비율에서 "40.000%"가 아닌 "40.0%"가 출력된다.
이를 해결하기 위해 String.format을 사용하였다.
관련 포스팅
[백준 4344번] - 평균은 넘겠지 (Java)
todayilearned.Algorithm.solveProblem(4344)
velog.io
[Java] String.format 을 이용한 문자열 형식 설정하기
public static String format(String format, Object... args); public static String format(Locale l, String format, Object... args); String 의 static 메서드인 format 메서드는 문자열의 형식을 설정하는..
blog.jiniworld.me
'Java > 백준' 카테고리의 다른 글
[10809] 알파벳 찾기 (0) | 2022.06.26 |
---|---|
[1065] 한수 (0) | 2022.06.25 |
[8958] OX퀴즈 (0) | 2022.06.24 |
[1546] 평균 (0) | 2022.06.23 |
[3052] 나머지 (0) | 2022.06.23 |