//_7_6_main.cpp
#include "GradeBook.h"
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int gradesArraySize = 10;
int gradesArray[gradesArraySize];
//随机产生学生成绩
srand((unsigned)time(NULL));
for(int i=0;i<gradesArraySize;i++)
{
gradesArray[i] = rand()%101 ;
}
GradeBook myGradeBook("C++",gradesArray);
myGradeBook.displayMessage();
myGradeBook.processGrades();
system("pause >> cout");
return 0;
}
//GradeBook.h #include <string> using namespace std; class GradeBook { public: //要设置成静态的const常量,,, static const int students = 10;//参加考试的学生 GradeBook(string,const int[]); void setCourseName(string); string getCourseName(); void displayMessage();//打印一条欢迎信息! void processGrades();//综合下面函数的功能,,,, int getMaximum();//得到学生成绩中的最大值 int getMinimum();//得到学生成绩中的最小值 double getAverage();//计算该门课程学生成绩的平均值 void outputBarChart();//输出学生成绩的柱状图 void outputGrades();//输出学生的成绩 private: string courseName;//专业名称 int grades[students];//学生成绩的数组 };
//GradeBook.cpp
#include "GradeBook.h"
#include <iostream>
#include <iomanip>
using namespace std;
GradeBook::GradeBook(string name,const int a[])
{
setCourseName(name);
for(int i=0;i<students;i++)//将调用的数组信息复制到类的对象的数组中
grades[i] = a[i] ;
}
void GradeBook::setCourseName(string name)
{
courseName = name;
}
string GradeBook::getCourseName()
{
return courseName;
}
void GradeBook::displayMessage()//打印一条欢迎信息!
{
cout << "Welcome to the grade book for\n"
<< getCourseName() << " !" << endl;
}
void GradeBook::processGrades()//综合下面函数的功能,,,,
{
outputGrades();//先输出学生成绩:
cout << "Class average is " << setprecision(2) << fixed <<getAverage() << endl;
cout << "Lowest grade is " << getMinimum() << endl;
cout << "Highest grade is " << getMaximum() << endl;
outputBarChart();
}
int GradeBook::getMaximum()//得到学生成绩中的最大值
{
int max = 0;
for(int k=0;k<students;k++)
{
if(max<grades[k])
max = grades[k];
}
return max;
}
int GradeBook::getMinimum()//得到学生成绩中的最小值
{
int min = 100;
for(int k=0;k<students;k++)
{
if(min>grades[k])
min = grades[k];
}
return min;
}
double GradeBook::getAverage()//计算该门课程学生成绩的平均值
{
int sum = 0;
for(int k=0;k<students;k++)
sum+=grades[k];
return (static_cast<double>(sum))/students ;
}
void GradeBook::outputBarChart()//输出学生成绩的柱状图
{
cout << "\nGrades distribution:" << endl;//学生的成绩分布
const int frequencySize = 11;
int frequency[frequencySize] = {0};
for(int i=0;i<students;i++)
frequency[grades[i]/10] ++ ;
for(int count=0;count<frequencySize;count++)
{
if(count == 0)
cout << " 0-9:" ;
else if(count == 10)
cout << " 100:" ;
else
cout << count*10 << "-" << count*10 + 9 << ":" ;
for(int star=0;star<frequency[count];star++)
cout << "*" ;
cout << endl;
}
}
void GradeBook::outputGrades()//输出学生的成绩
{
cout << "\nThe grades are :" << endl;
for(int student=0;student<students;student++)
cout << "Student" << setw(2) << (student+1)
<< " : " << setw(4) << grades[student]
<< endl;
cout << endl;
}
程序运行结果: