
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和sd
cout << "高于平均分数加一个标准偏差的同学人数:" << 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 function
double countCourseMean(); // 平均分
double countCourseSd(); // 标准偏差
private:
vector<double> scores;
int above;
int between;
int below;
double mean; // 平均分
double sd; // 标准差
void classifyScores(); // 分类成绩
};

306

被折叠的 条评论
为什么被折叠?



