jeongwon
[백준 JAVA] 1546번 - 평균 본문
예제가 길어 문제는 링크로 대체 : https://www.acmicpc.net/problem/1546
1546번: 평균
첫째 줄에 시험 본 과목의 개수 N이 주어진다. 이 값은 1000보다 작거나 같다. 둘째 줄에 세준이의 현재 성적이 주어진다. 이 값은 100보다 작거나 같은 음이 아닌 정수이고, 적어도 하나의 값은 0보
www.acmicpc.net
틀린 답안 :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
double max = 0;
double total=0;
double[] score = new double[Integer.parseInt(br.readLine())];
st= new StringTokenizer(br.readLine()," ");
for(int i=0; i<score.length; i++)
score[i]=Double.parseDouble(st.nextToken());
for(int i=0; i<score.length-1; i++) {// 1, 50 예제를 입력하면 결과 Infinity로 나옴
if(score[i]>=score[i+1]) max=score[i];
else max=score[i+1];
}
for(int i=0; i<score.length; i++) {
score[i]=(score[i]/max)*100;
total+=score[i];
}
System.out.println(total/score.length);
br.close();
}
}
배열의 비교할 대상인 다음 인덱스 [i+1]가 없는 상황이었다.
수정 답안:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
double[] score = new double[Integer.parseInt(br.readLine())];
st= new StringTokenizer(br.readLine()," ");
for(int i=0; i<score.length; i++)
score[i]=Double.parseDouble(st.nextToken());
double max = 0;
double total=0;
Arrays.sort(score); // 손쉽게 정렬
max=score[score.length-1]; //후 max값을 구할 수 있다.
for(int i=0; i<score.length; i++) {
score[i]=(score[i]/max)*100;//굳이 배열에 다시 저장할 필요는 없는 값.
total+=score[i];
}
System.out.println(total/score.length);
br.close();
}
}
그러나 지저분해 보이는 코드.
개선 답안 :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double[] score = new double[Integer.parseInt(br.readLine())];
StringTokenizer st= new StringTokenizer(br.readLine()," ");
for(int i=0; i<score.length; i++)
score[i]=Double.parseDouble(st.nextToken());
double total=0;
Arrays.sort(score);
for(int i=0; i<score.length; i++)
total+=(score[i]/score[score.length-1])*100; //바로 total에 저장
System.out.println(total/score.length);
br.close();
}
}
max 변수 또한 굳이 생성하지 않아도 되었다.
개선 답안 출처는 오늘도 역시 : https://st-lab.tistory.com/47
'오늘의 문제' 카테고리의 다른 글
| [백준 JAVA] 4344번 - 평균은 넘겠지 (0) | 2022.05.30 |
|---|---|
| [백준 JAVA] 8958번 - OX 퀴즈 (0) | 2022.05.28 |
| [백준 JAVA] 3052번 - 나머지 (0) | 2022.05.27 |
| [백준 JAVA] 2577번 - 숫자의 개수 (0) | 2022.05.26 |
| [백준 JAVA] 2562번 - 최댓값 (0) | 2022.05.25 |