백준 BOJ C# 1546 평균
2020. 1. 22. 22:27ㆍ백준 알고리즘 단계별/1차원 배열
반응형

백준 BOJ C# [1546] [평균]
출제 링크 : https://www.acmicpc.net/problem/1546
1546번: 평균
첫째 줄에 시험 본 과목의 개수 N이 주어진다. 이 값은 1000보다 작거나 같다. 둘째 줄에 세준이의 현재 성적이 주어진다. 이 값은 100보다 작거나 같은 음이 아닌 정수이고, 적어도 하나의 값은 0보다 크다.
www.acmicpc.net
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using static System.Console; | |
namespace baekioon | |
{ | |
class MainApp | |
{ | |
static void Main() | |
{ | |
// 최고 점수로 비교될 변수 | |
float saveNum = 0; | |
// 평균값이 될 변수 | |
float average = 0; | |
// 시험 본 과목의 개수 N | |
int n = int.Parse(ReadLine()); | |
// 세준이의 현재 성적 | |
string[] inputNum = ReadLine().Split(); | |
// string 배열을 float 배열로 변환 | |
// - 절대/상대 오차 범위를 위해서 float형으로 만들어줌 | |
float[] fCurrentGrades = Array.ConvertAll(inputNum, float.Parse); | |
// 최고 점수를 구해줄 로직 | |
// - 현재 저장된 saveNum 과 입력받은 점수를 비교해서 | |
// - 큰 값을 saveNum에 저장함 | |
// - 결국 가장 큰 값이 saveNum에 저장 | |
for (int i = 0; i < n; i++) | |
{ | |
if (saveNum < fCurrentGrades[i]) | |
{ | |
saveNum = fCurrentGrades[i]; | |
} | |
} | |
// 가짜점수, 평균 로직 | |
// - (점수/최고점수) * 100 계산 수행뒤 배열에 넣어줌 | |
// - 그리고 평균값 변수에 값을 더해줌 | |
for (int i = 0; i < n; i++) | |
{ | |
fCurrentGrades[i] = (fCurrentGrades[i] /saveNum ) * 100; | |
average += fCurrentGrades[i]; | |
} | |
// 평균값으로 계산한뒤 | |
average = average / n; | |
// 출력 | |
WriteLine($"{average:F2}"); | |
} | |
} | |
} |
우선 입력받는 배열이 float형 이라는 점과
마지막 평균을 출력하는 stringFormat을 활용해야된다.
c# 은 6.0이후부터 문자열 보간 이라는 기능을 지원한다.
stringformat 정보는 여기서 찾았다.
https://docs.microsoft.com/ko-kr/dotnet/csharp/tutorials/string-interpolation
C#의 문자열 보간
문자열 보간을 사용하여 C#으로 결과 문자열에 서식이 지정된 식 결과를 포함하는 방법을 알아봅니다.
docs.microsoft.com
반응형