C++之Count类
main.cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "Count.h"using namespace std;int main()
{srand(time(0)); // 初始化随机数种子GradeCounter classScore;// 测试:使用随机数生成100个成绩for (int i = 0; i < 100; ++i) {double score = (40.0 + (rand() % (int)(97.5 * 10 + 1)) / 10.0); // 生成40.0到97.5之间的浮点数classScore.addScore(score); //classScore.scores.push_back(score);}classScore.outputResults(); // 输出结果return 0;
}
Count.cpp
#include "Count.h"
#include <cmath>
using namespace std;void GradeCounter::addScore(double grade)
{scores.push_back(grade);
}double GradeCounter::countCourseMean() // 平均分
{double sum = 0;for (double s : scores) {sum += s;}return sum / scores.size();
}double GradeCounter::countCourseSd() // 标准偏差
{mean = countCourseMean();double sum = 0;for (double s : scores){sum += (s - mean) * (s - mean);}return sqrt(sum / scores.size());
}void GradeCounter::classifyScores() // // 分类成绩
{sd = countCourseSd();for (double s : scores){if (s > mean + sd) {above++;}else if (s < mean - sd) {below++;}else {between++;}}
}void GradeCounter::outputResults()
{cout << "这学期 C++的平均分数为:" << countCourseMean() << endl;cout << "标准偏差为:" << countCourseSd() << endl;classifyScores(); // 重新分类以使用最新的mean和sdcout << "高于平均分数加一个标准偏差的同学人数:" << above << endl;cout << "介于平均分数加、减一个标准偏差的同学人数:" << between << endl;cout << "低于平均分数减一个标准偏差的同学人数:" << below << endl;
}
Count.h
#include <iostream>
#include <vector>using namespace std;class GradeCounter
{
public:void outputResults(); // 输出void addScore(double grade); // to avoid use private member by using this functiondouble countCourseMean(); // 平均分double countCourseSd(); // 标准偏差private:vector<double> scores;int above;int between;int below;double mean; // 平均分double sd; // 标准差void classifyScores(); // 分类成绩
};