定义一个学生的结构体,每个学生的数据包括学号、英语、数学、物理三门课的成绩。 定义运算符重载函数,完成对学生物理成绩的比较。定义一个包含 60 个学生的结构体数组 表示 60 个学生的信息,要求如下: ①初始化 60 个学生的具体信息(学号,英语成绩、数学成绩、物理成绩);各科成绩均 为 60~100 之间的随机数。 ②定义函数,完成对学生的排序(使用运算符重载)
#include <iostream>
using namespace std;
struct Stu
{
int id;
int y, s, w;
int operator>(struct Stu &stu)
{
return w > stu.w;
}
int operator<(struct Stu &stu)
{
return w < stu.w;
}
friend ostream &operator<<(ostream &os, Stu &stu)
{
os << stu.id << " " << stu.y << " " << stu.s << " " << stu.w;
return os;
}
};
void stusort(Stu stu[])
{
Stu t;
for (int i = 0; i < 59; i++)
{
for (int j = i + 1; j < 60; j++)
{
if (stu[i] < stu[j])
{
t = stu[i];
stu[i] = stu[j];
stu[j] = t;
}
}
}
}
int main()
{
Stu stu[60];
srand(time(NULL));
for (int i = 0; i < 60; i++)
{
stu[i].id = i + 1;
stu[i].y = rand() % 41 + 60;
stu[i].s = rand() % 41 + 60;
stu[i].w = rand() % 41 + 60;
}
stusort(stu);
for (int i = 0; i < 60; i++)
cout << stu[i] << endl;
return 0;
}