문제 링크: https://www.acmicpc.net/problem/4344
백준 1차원 배열 9단계 - 4344번 평균은 넘겠지를 풀어보았다.
풀이: 비율을 셋째 자리까지 반올림해 출력한다.
C++의 경우, cin으로 같은 행에 있는 값 중 하나만 받아올 수 있다는 점을 알게 되었고(학생 수를 받아올 때), 반올림해 소수 셋째 자리까지 나타낼 때 cout<<fixed와 cout.precision()을 이용하면 된다는 것을 알게 되었다. (cmath에 있는 round를 쓰는 방법은 오답이 나왔다. 왜인지는 모르겠다)
파이썬의 경우, f"{실수:.표기할 자리수f}" 형식을 사용해 출력하게 했다.
C++
#include <iostream>
using namespace std;
int main()
{
int c,num;
cin>>c;
int arr[1000]={0,};
double mean;
for(int i=0;i<c;i++)
{
cin>>num; // 학생 수
int sum=0;
for(int j=0;j<num;j++)
{
cin>>arr[j];
sum+=arr[j];
}
mean=(double)sum/(double)num; // 평균
int count=0;
for(int j=0;j<num;j++)
{
if(arr[j]>mean) count++;
}
double res= (double)count/(double)num*100; // 비율
cout<<fixed; // 소수점 셋째 자리 반올림
cout.precision(3);
cout<<res<<"%"<<"\n";
}
}
Python
c=int(input())
for i in range(c):
sre=list(map(int,input().split()))
mean=0
n=sre[0]
del sre[0]
for j in range(n):
mean+=sre[j]
mean/=n
per=0
for j in range(n):
if(sre[j]>mean): per+=1
per=per/n*100
print(f'{round(per,3):.3f}%') # 포맷팅을 잘하자!
'코테용 문제풀이 > 백준' 카테고리의 다른 글
셀프 넘버 풀이 (0) | 2022.12.31 |
---|---|
정수 N개의 합 풀이 (0) | 2022.12.31 |
OX퀴즈 풀이 (0) | 2022.12.31 |
평균 풀이 (0) | 2022.12.31 |
나머지 풀이 (0) | 2022.12.31 |