본문 바로가기

Beakjoon/else

[백준] 10984번 내 학점을 구해줘 (C++)

문제

https://www.acmicpc.net/problem/10984

 

10984번: 내 학점을 구해줘

게으른 근우는 열심히 놀다가 문득, 자신의 학점 평균이 얼마일지 궁금해졌다. 학사시스템도 들어가기 귀찮아하는 근우를 위해 구해주도록 하자. 

www.acmicpc.net

코드

#include <iostream>
#include <cmath>

using namespace std;

int main(){
  int t;
  cin >> t;
  for(int i=0; i<t; i++){
    int n;
    cin >> n;
    int credit = 0;
    double gpa = 0;
    for(int j=0; j<n; j++){
      int c;
      double g;
      cin >> c >> g;
      credit+=c;
      gpa+=c*g;
    }
    gpa/=credit;
    printf("%d %.1f\n", credit, round(gpa*10)/10);
  }

  return 0;
}

정리

n번째 자리 숫자까지 올림, 내림, 반올림 하는 방법

<cmath> 헤더에 ceil(올림), floor(내림), round(반올림),  함수가 있다.

#include <iostream>
#include <cmath>

using namespace std;

int main(){
  double d = 1.23456789;

  // 첫 번째 자리까지 올림, 내림, 반올림
  printf("%.1f %.1f %.1f\n", ceil(d*10)/10, floor(d*10)/10, round(d*10)/10);

  // 두 번째 자리까지 올림, 내림, 반올림
  printf("%.2f %.2f %.2f\n", ceil(d*100)/100, floor(d*100)/100, round(d*100)/100);

  return 0;
}

 

+ 출력을 할때 마지막에 '\n'를 안해줘서 애를 먹었던 문제다. 출력형태를 잘 보고 '\n'를 까먹지 말자!

참조

https://jaimemin.tistory.com/958

https://psychoria.tistory.com/769