题目:
建立一个学生类,输入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+的人数不足两人,骚年重新来过吧";
}
}