gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
用c++写,5个学生,4门课
- User
用c++写,5个学生,4门课
- Assistant
下面是一个使用C++编写的简单示例,演示了如何处理5个学生的4门课程成绩。每个学生有唯一的编号,每门课程也有唯一的编号。请注意,这只是一个基本示例,你可能需要根据自己的需求进行修改和扩展。
#include <iostream> #include <vector> using namespace std; struct Student { int id; vector<double> scores; }; int main() { const int NUM_STUDENTS = 5; const int NUM_COURSES = 4; vector<Student> students; // 输入学生信息和成绩 for (int i = 0; i < NUM_STUDENTS; i++) { Student student; student.id = i + 1; cout << "请输入学生" << student.id << "的成绩:" << endl; for (int j = 0; j < NUM_COURSES; j++) { double score; cout << "请输入第" << j + 1 << "门课程的成绩:"; cin >> score; student.scores.push_back(score); } students.push_back(student); } // 输出学生信息和成绩 cout << "学生信息和成绩:" << endl; for (const auto& student : students) { cout << "学生" << student.id << "的成绩为:"; for (const auto& score : student.scores) { cout << score << " "; } cout << endl; } return 0; }这段代码首先定义了一个
Student结构体,其中包含学生的学号(id)和成绩(scores)。然后,通过vector<Student>来存储学生的信息。在
main()函数中,首先定义了常量NUM_STUDENTS和NUM_COURSES代表学生人数和课程数量。然后,通过循环输入每个学生的成绩,并将其保存在students向量中。接下来,通过循环遍历
students向量,输出每个学生的学号和成绩。你可以根据自己的需要对该代码进行修改和扩展。
- User
不使用容器来完成
- Assistant
如果你不想使用容器来完成这个任务,也可以使用C++数组来存储学生和课程的成绩。下面是一个不使用容器的示例代码:
#include <iostream> using namespace std; const int NUM_STUDENTS = 5; const int NUM_COURSES = 4; struct Student { int id; double scores[NUM_COURSES]; }; int main() { Student students[NUM_STUDENTS]; // 输入学生信息和成绩 for (int i = 0; i < NUM_STUDENTS; i++) { students[i].id = i + 1; cout << "请输入学生" << students[i].id << "的成绩:" << endl; for (int j = 0; j < NUM_COURSES; j++) { cout << "请输入第" << j + 1 << "门课程的成绩:"; cin >> students[i].scores[j]; } } // 输出学生信息和成绩 cout << "学生信息和成绩:" << endl; for (int i = 0; i < NUM_STUDENTS; i++) { cout << "学生" << students[i].id << "的成绩为:"; for (int j = 0; j < NUM_COURSES; j++) { cout << students[i].scores[j] << " "; } cout << endl; } return 0; }在这段代码中,我们使用了一个长度为
NUM_STUDENTS的Student数组来存储学生信息。每个学生都有一个学号(id)和一个大小为NUM_COURSES的成绩数组(scores)。通过循环输入每个学生的成绩,并将其保存在
students数组中。然后,通过循环遍历
students数组,输出每个学生的学号和成绩。这个示例代码与使用容器的代码相比,只是使用了数组来替代了向量的存储方式。你可以根据自己的需要对代码进行修改。