(c++)输入整数n(小于10),再依次输入n个学生的学号(整数)、姓名(string)、一门课的成绩(整数),按照成绩从小到大输出所有学生的信息。
格式提醒:每一项信息在输出的时候都有空格,每个学生的信息占一行。
该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
以下是一个用 C++ 实现题目要求的示例代码,其中使用结构体存储学生信息:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Student {
int id;
string name;
int score;
};
bool compareStudent(const Student &s1, const Student &s2) {
return s1.score < s2.score;
}
int main() {
int n;
cin >> n;
Student students[n];
for (int i = 0; i < n; i++) {
cin >> students[i].id >> students[i].name >> students[i].score;
}
sort(students, students + n, compareStudent);
for (int i = 0; i < n; i++) {
cout << students[i].id << " " << students[i].name << " " << students[i].score << endl;
}
return 0;
}
代码中,首先通过 cin
输入学生人数 n
,然后定义一个结构体 Student
存储每个学生的信息,包括学号、姓名和成绩。接着,使用循环依次输入每个学生的信息,并将其存储在一个长度为 n
的数组中。然后,使用 sort
函数按照成绩从小到大排序学生信息。最后,使用循环输出排序后的学生信息。
请注意,本代码未对输入进行错误处理,如有需要请自行添加。
如果以上回答对您有所帮助,点击一下采纳该答案~谢谢
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Student{
int id;
string name;
int score;
};
bool cmp(Student a, Student b){
return a.score < b.score;
}
int main(){
int n;
cin >> n;
Student students[n];
for(int i=0; i<n; i++){
cin >> students[i].id >> students[i].name >> students[i].score;
}
sort(students, students+n, cmp);
for(int i=0; i<n; i++){
cout << students[i].id << " " << students[i].name << " " << students[i].score << endl;
}
return 0;
}
以下是一个用 C++ 实现的示例代码,可以实现你所需的功能:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Student {
int id;
std::string name;
int score;
};
bool compare_score(const Student& s1, const Student& s2) {
return s1.score < s2.score;
}
int main() {
int n;
std::cin >> n;
std::vector<Student> students(n);
for (int i = 0; i < n; i++) {
std::cin >> students[i].id >> students[i].name >> students[i].score;
}
std::sort(students.begin(), students.end(), compare_score);
for (const auto& s : students) {
std::cout << s.id << " " << s.name << " " << s.score << std::endl;
}
return 0;
}
首先,我们定义一个 Student
结构体,用来存储学生的学号、姓名和成绩。然后,我们定义一个比较函数 compare_score
,用于按照成绩从小到大排序。
在 main
函数中,我们首先输入学生的数量 n
,然后创建一个长度为 n
的 students
向量,并依次输入每个学生的学号、姓名和成绩。接下来,使用 std::sort
函数对 students
向量进行排序,排序方式使用 compare_score
函数。最后,依次输出每个学生的学号、姓名和成绩,每个学生的信息占一行。
希望这个示例代码可以帮助你完成你的任务。