C++ 实验作业

该代码示例定义了一个C++的学生类,包含学号、分数和人数属性。程序要求输入N个学生数据,当80分以上学生大于等于2人时,从这些高分学生中随机选择一人并输出其学号和分数。程序使用了构造函数、向量容器和随机数生成进行实现。
摘要由CSDN通过智能技术生成

题目:

建立一个学生类,输入N个学生的学号和分数,要求80分以上(不含80分)的>=2人,(可选用链表保存).构造函数规定人数N.从80分以上的学生中随机抽取一个人并且输出其学号和分数.要求抽取是没有冗余操作.注意:用类编程,类内要有构造函数.

题解:

#include<iostream>
#include<math.h>
#include<vector>
#include<string.h>
#include<stdlib.h>
using namespace std;


class Student {

    
public:
    string num;
    int score;
    int N;//人数
    Student(string num, int score)//构造函数1
    {
        this->num = num;
        this->score = score;
    }
    Student(string num, int score, int N)//构造函数2
    {
        this->num = num;
        this->score = score;
        this->N = N;
    }
};
int select(vector<Student> stu,int len)//随机抽取
{
    //设置随机数,从stud集合里选一个学生
    int choice = rand() % len ;
    return choice;
}
int main()
{
    vector<Student> stu;
    int flag = 0; //记录80+的人数
    string num;
    int score;
    int N;

    cout << "请输入总人数: ";
    cin >> N;
    cout << "请输入学号: ";
    cin >> num;
    cout << "请输入分数: ";
    cin >> score;
    

    Student student(num, score, N);
    stu.push_back(student);
    
    if (score > 80)
        flag++;

    while (1)
    {
        for (int i = 1; i < N; i++)
        {

            cout << "请继续输入学号: ";
            cin >> num;
            cout << "请继续输入分数: ";
            cin >> score;

            Student student(num, score);
            stu.push_back(student);

            
            if (score > 80)
                flag++;

        }
        if (flag >= 2)
        {
            int i = 0;
            vector<Student> stud; //80+的学生集合
            for (; i < stu.size(); i++)
            {
                if (stu[i].score > 80)
                    stud.push_back(stu[i]);
            }
            int len = stud.size();
            cout << "随机选中学号为: " << stu[select(stud, len)].num << "    随机选中分数为: " << stu[select(stud, len)].score;
            break;
        }
        else
            cout << "80+的人数不足两人,骚年重新来过吧";

    }
    


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值