结构体应用

成绩统计:输入N个学生的姓名和语文、数学的得分,输出每个学生的总分。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
struct student_struct{
    string name;
    int  chinese;
    int  math;
    int total;
};
int main(){
    student_struct   students[30];
    int students_number;
    cout<<"Please input the number of students";
    cin>>students_number;
    for (int i = 0; i <students_number ; ++i) {
        cin>>students[i].name;
        cin>>students[i].chinese;
        cin>>students[i].math;
        students[i].total=students[i].chinese+students[i].math;
        }
    for (int j = 0; j <students_number ; ++j) {
        cout<<students[j].name<<" "<<students[j].chinese;
        cout<<" "<<students[j].math<<" "<<students[j].total<<endl;
    }
}

习题一:有n个同学(n<30),每个学生的数据包括学号、姓名、英语、语文、数学三门课的成绩,从键盘输入个学生数据,要求打印出3门课程的总分为最高分的学生的数据(包括学号,姓名,总分数)。

成绩统计:输入N个学生的姓名和语文、数学的得分,按成绩由高到低顺序,输出每个学生的信息。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
 struct student_struct{
     string name;
     int  chinese;
     int  math;
     int total;
 };
 int main(){
     student_struct   students[30];
     int students_number;
     cout<<"Please input the number of students:";  
     cin>>students_number;
     for (int i = 0; i <students_number;i++){
         cin>>students[i].name;
         cin>>students[i].chinese;
         cin>>students[i].math;
         students[i].total=students[i].chinese+students[i].math;
         }
      for (int last =students_number-1;last>0;--last) {
         for (int i = 0; i <last ; ++i) {
             if(students[i].total<students[i+1].total)
                 swap(students[i],students[i+1]);
         }
     }
     for (int j = 0; j <students_number ; ++j) {
         cout<<students[j].name<<" "<<students[j].chinese;
         cout<<" "<<students[j].math<<" "<<students[j].total<<endl;
     }
 }
Scroll to Top