[Softeer] 성적 평균 -Java

yseo14·2024년 10월 30일

코딩테스트 대비

목록 보기
26/88


문제 링크

오토에버 코테를 소프티어로 본다고 해서 연습할 겸 풀었다.
코테가 레벨3 수준이라는데 너무 쉬운 문제 아닌가 싶었다.

풀이

입력 받은 성적들을 배열에 저장하고 구간 범위 내에 점수들의 평균을 구한다.
소수점 둘째자리까지 출력하는걸 몰라서 구글링 후 풀이했다.

코드

import java.io.*;
import java.util.*;

public class Main {
    
    static int N;
    static int K;
    static Double avg;
    static int[] scores;
    
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());
        scores = new int[N];
        
        st = new StringTokenizer(br.readLine());
        for(int i =0;i<N;i++){
            scores[i] = Integer.parseInt(st.nextToken());
        }

        for(int i = 0;i<K;i++){
            st = new StringTokenizer(br.readLine());
            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());
            Double result = getAvg(start, end);
            String formatted = String.format("%.2f", result);
            System.out.println(formatted);
        }
    }

    public static Double getAvg(int start, int end){
        int startIdx = start -1;
        int endIdx = end-1;
        Double sum = 0.0;
        for(int i=startIdx;i<=endIdx;i++){
            sum+=scores[i];
        }
        Double avg = sum/(end-start+1);
        return Double.parseDouble(String.valueOf(avg));
    }
}

소수점 반올림 구하기

1. String.format()

String doubleStr = String.format("%.nf", number);

n에 소수점 몇번째자리까지 표현하고 싶은지 넣어주면 된다.

2. Math.round()

Math.round()는 괄호 안에 수를 반올림하여 정수로 나타낸다. 즉, Math.round(326.7) 같은 경우는 327을 반환한다.
따라서 3.2678을 소수점 둘째자리까지 반올림하여 표현하고 싶다면 아래와 같이 사용하면 된다.

double roundNum = Math.round(3.2678 * 100.0) / 100.0;	
// 100을 곱하여 326.78이 된 수를 반올림하여 정수로 나타내면 327
// 327을 100.0으로 나누어 3.27로 만들어준다. 
profile
like the water flowing

0개의 댓글