#include <iostream> #include <iomanip>
using namespace std;
int main() { /* 변수 초기화 total: 입력된 점수의 총합 gradeCounter:입력되는 점수 개수 a~fCount: 입력된 점수를 알파벳 성적으로 바꾸어 세어 넣음*/ int total{ 0 }; unsigned int gradeCounter{ 0 }; unsigned int aCount{ 0 }; unsigned int bCount{ 0 }; unsigned int cCount{ 0 }; unsigned int dCount{ 0 }; unsigned int fCount{ 0 };
/* 입력 안내 프롬프트 */ cout << "Enter the integer grades in the range 0 - 100." << endl << "Type the end-of-file indicator to terminate input:" << endl << " On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter\n" << " On Windows type <Ctrl> z then press Enter\n";
int grade;
/* 점수를 계속 입력 받음 eof 지시자가 입력될 때까지 */ while (cin >> grade) { total += grade; ++gradeCounter;
/* 입력된 점수를 해당 a~f 점수로 변환하여 각각 수를 세어줌 switch문 괄호의 값에 맞는 case문으로 이동하여 실행. case문 여러개가 동일한 실행을 할 경우, case 9: case 10: 실행... 과 같이 나란히 사용. case문의 끝에break를 사용하여 switch 문을 벗어남. */ switch (grade / 10) { case 9: case 10: ++aCount; break; case 8: ++bCount; break; case 7: ++cCount; break; case 6: ++dCount; break; default: ++fCount; break; // 마지막에는 구지 안 붙여도 되지만, 어찌됐든 사용. } }
/* iomanip에 있는 기능을 사용 고정 소숫점 2자리로 설정 */ cout << fixed << setprecision(2);
cout << "\nGrade Report:\n";
/* 0으로 나누어지는 것을 방지하기 위한 if */ if (gradeCounter != 0) { /* static_cast로 형변환을 하여주지 않으면 결과가 정수로 나온다. */ double average = static_cast<double>(total) / gradeCounter;
cout << "Total of the " << gradeCounter << " grades entered is " << total << "\nClass average is " << average << "\nNumber of students who received each grade:" << "\nA: " << aCount << "\nB: " << bCount << "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl; } else { cout << "No grades were entered" << endl; } } |
결과
Enter the integer grades in the range 0 - 100.
Type the end-of-file indicator to terminate input:
On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter
On Windows type <Ctrl> z then press Enter
99
54
96
67
71
75
88
100
90
85
^Z
Grade Report:
Total of the 10 grades entered is 825
Class average is 82.50
Number of students who received each grade:
A: 4
B: 2
C: 2
D: 1
F: 1
설명은 주석으로 대체한다.