Black.: 操作题1 定义Student类,包含三个属性:学号number(int),年级state(int),成绩score(float);键盘输入20个学生对象,学号为1~20个,年级(1~4)和成绩(0~100,要为浮点数)都由随机数确定。 实现功能:1.打印出4年级(即state==4时)的学生信息;2.使用冒泡排序按学生成绩降序排序,并遍历所有学生信息。 Black.: [图片]
时间: 2023-05-19 08:02:44 浏览: 99
C知道: 以下是定义Student类的代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Student {
public:
int number;
int state;
float score;
};
int main() {
srand(time(NULL)); // 初始化随机数种子
Student students[20];
for (int i = 0; i < 20; i++) {
students[i].number = i + 1;
students[i].state = rand() % 4 + 1;
students[i].score = rand() % 101 / 10.0;
}
cout << "4年级学生信息:" << endl;
for (int i = 0; i < 20; i++) {
if (students[i].state == 4) {
cout << "学号:" << students[i].number << " 年级:" << students[i].state << " 成绩:" << students[i].score << endl;
}
}
cout << "按成绩降序排序后的学生信息:" << endl;
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19 - i; j++) {
if (students[j].score < students[j + 1].score) {
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
for (int i = 0; i < 20; i++) {
cout << "学号:" << students[i].number << " 年级:" << students[i].state << " 成绩:" << students[i].score << endl;
}
return 0;
}
```
这段代码定义了一个名为Student的类,包含三个属性:学号number、年级state和成绩score。然后在主函数中,使用随机数生成20个学生对象,并按照要求打印出4年级学生信息和按成绩降序排序后的学生信息。
注意:这段代码中使用了srand函数来初始化随机数种子,以保证每次运行程序生成的随机数都不同。
阅读全文
相关推荐















