以下是使用switch语句编写的C++代码,实现了输入学生成绩、计算平均成绩、计算全班平均成绩和排序成绩的功能:#include <iostream>using namespace std;const int MAX_STUDENTS = 50;const int MAX_SUBJECTS = 5;int grades[MAX_STUDENTS][MAX_SUBJECTS];float studentAverages[MAX_STUDENTS];float subjectAverages[MAX_SUBJECTS];void inputGrades() { cout << "Enter grades for each student: " << endl; for (int i = 0; i < MAX_STUDENTS; i++) { cout << "Student " << i+1 << ": "; for (int j = 0; j < MAX_SUBJECTS; j++) { cin >> grades[i][j]; } }}void calculateStudentAverages() { for (int i = 0; i < MAX_STUDENTS; i++) { int total = 0; for (int j = 0; j < MAX_SUBJECTS; j++) { total += grades[i][j]; } studentAverages[i] = (float)total / MAX_SUBJECTS; }}void calculateSubjectAverages() { for (int j = 0; j < MAX_SUBJECTS; j++) { int total = 0; for (int i = 0; i < MAX_STUDENTS; i++) { total += grades[i][j]; } subjectAverages[j] = (float)total / MAX_STUDENTS; }}void sortStudentAverages() { for (int i = 0; i < MAX_STUDENTS - 1; i++) { for (int j = i + 1; j < MAX_STUDENTS; j++) { if (studentAverages[j] > studentAverages[i]) { float temp = studentAverages[i]; studentAverages[i] = studentAverages[j]; studentAverages[j] = temp; } } }}void printStudentAverages() { cout << "Student averages: " << endl; for (int i = 0; i < MAX_STUDENTS; i++) { cout << "Student " << i+1 << ": " << studentAverages[i] << endl; }}void printSubjectAverages() { cout << "Subject averages: " << endl; for (int j = 0; j < MAX_SUBJECTS; j++) { cout << "Subject " << j+1 << ": " << subjectAverages[j] << endl; }}int main() { int choice; do { cout << "Menu:" << endl; cout << "1. Input grades" << endl; cout << "2. Calculate student averages" << endl; cout << "3. Calculate subject averages" << endl; cout << "4. Sort student averages" << endl; cout << "5. Quit" << endl; cout << "Enter your choice: "; cin >> choice; switch (choice) { case 1: inputGrades(); break; case 2: calculateStudentAverages(); printStudentAverages(); break; case 3: calculateSubjectAverages(); printSubjectAverages(); break; case 4: calculateStudentAverages(); sortStudentAverages(); printStudentAverages(); break; case 5: cout << "Exiting program..." << endl; break; default: cout << "Invalid choice!" << endl; } } while (choice != 5); return 0;}
此代码利用switch语句实现了一个菜单,用户可以选择不同的操作来输入成绩、计算平均成绩、计算全班平均成绩和排序学生平均成绩。根据用户的选择,程序将调用相应的函数来执行对应的操作。
希望以上代码能满足你的需求。如果还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要! |