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和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(); // 分类成绩
};

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值