目录
题目
代码
运行命令(在控制台输入)
运行截图
题目
(修改GradeBook)修改图5.9~图5.11所示的 GradeBook 程序,使它计算一组成绩的平均成绩。
成绩A为4分,成绩B为3分,依次类推。
A:4
B:3
C:2
D:1
E:0
F:-1
代码
注意有注释的位置,基本都是有修改的地方。
//5_15.h
// GradeBook.h
#include <string>
class GradeBook
{
public:
GradeBook(std::string);
void setCourseName(std::string);
std::string getCourseName() const;
void setCourseTeacher(std::string);
std::string getCourseTeacher() const;
void displayMessage() const;
void inputGrades();
void displayGradeReport() const;
private:
std::string courseName;
unsigned int aCount;
unsigned int bCount;
unsigned int cCount;
unsigned int dCount;
unsigned int eCount;
unsigned int fCount;
double gradeSum;//增加了存储分数和的变量
};
//5_15.cpp
#include <iostream>
#include "5_15.h"
#include <iomanip>
using namespace std;
GradeBook::GradeBook(string name) : aCount(0), bCount(0), cCount(0), dCount(0), eCount(0), fCount(0)
{
setCourseName(name);
}
void GradeBook::setCourseName(string name)
{
if (name.size() <= 25)
courseName = name;
else
{
courseName = name.substr(0, 25);
cerr << "name\"" << name << "\"exceeds maximum length(25).\n"
<< "Limiting courseName to first 25 characters.\n"
<< endl;
}
}
string GradeBook::getCourseName() const
{
return courseName;
}
void GradeBook::displayMessage() const
{
cout << "Welcome to the grade book for " << getCourseName() << endl;
}
void GradeBook::inputGrades() // 有修改
{
int grade;
gradeSum = 0.0; // 初始化
cout << "Enter the letter grades:" << endl
<< "Enter the EOF character to end input." << endl;
while ((grade = cin.get()) != EOF)
{
switch (grade)
{
case 'A':
case 'a':
aCount++;
gradeSum += 4; // 添加每个字母对应的分数
break;
case 'B':
case 'b':
bCount++;
gradeSum += 3;
break;
case 'C':
case 'c':
cCount++;
gradeSum += 2;
break;
case 'D':
case 'd':
dCount++;
gradeSum += 1;
break;
case 'E':
case 'e':
eCount++;
gradeSum += 0;
break;
case 'F':
case 'f':
fCount++;
gradeSum += (-1);
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered."
<< "\nPlease enter a new grade." << endl;
break;
}
}
}
void GradeBook::displayGradeReport() const//有修改
{
int count;
cout << "\n\nNumber of students who received each letter grade:"
<< "\nA:" << aCount << "\nB:" << bCount << "\nC:" << cCount
<< "\nD:" << dCount << "\nE:" << eCount << "\nF:" << fCount << endl;
count = aCount + bCount + cCount + dCount + eCount + fCount; // 求一共有多少个字母
cout << "这一组成绩的平均数:" << gradeSum / (static_cast<double>(count)) << endl; // 计算平均数
;
}
//5_15main.cpp
#include <iostream>
#include "5_15.h"
using namespace std;
int main()
{
GradeBook myGradeBook("zhang san");
myGradeBook.displayMessage();
myGradeBook.inputGrades();
myGradeBook.displayGradeReport();
return 0;
}
运行命令(在控制台输入)
g++ 5_15main.cpp 5_15.cpp -o 5_15.exe
5_15.exe
注意:如果输入5_15.exe执行不了,可以尝试使用 ./5_15.exe (别忘记最开始的点),我之前用这个命令执行的代码。
运行截图
最后,大家有问题欢迎一起交流,正在努力学习C++ ~~~