C言語・学生情報(P 1102)

12707 ワード

アルゴリズムトレーニングP 1102
時間制限:1.0 sメモリ制限:256.0 MB
    
4つのフィールド、名前、性別、年齢、成績を含む学生構造体タイプstudentを定義します.次に、メイン関数に構造体配列(長さ1000を超えない)を定義し、各要素の値を入力し、プログラムはバブルソート法を使用して学生を成績の小さい順にソートし、ソートの結果を出力します.
入力フォーマット:最初の行は整数N(N<1000)で、要素の数を表します.次に、N行の各行は要素を記述し、名前、性別は長さが20を超えない文字列で、年齢と成績はすべて整数です.
出力フォーマット:成績が小さいから大きいまですべての要素を出力し、複数の学生が成績が同じであれば、成績が同じ学生の間で元の入力順序を保持します.
入力:
  3
  Alice female 18 98
  Bob male 19 90
  Miller male 17 92
出力:
  Bob male 19 90
  Miller male 17 92
  Alice female 18 98
 
構造体でソートする方法を学んでから、この問題は簡単にできました.
コード1:
 1 #include
 2 #include<string.h> 
 3 #include
 4 #include
 5 #include
 6 /*       */
 7 typedef struct Stu{
 8     char name[30];
 9     char sex[20];
10     int age;
11     int score;
12 }stu;
13 /*        (  )  cmp: 
14                int;
15                    const void *;
16              ,      a b       ,    ,    0;
17 */ 
18 int cmp(const void *a,const void *b){
19     /* *(stu*)a   :a  void *  ,  
20      (stu*)    stu*  ,    *  ,
21       stu  ,      。*/
22     stu c=*(stu*)a;
23     stu d=*(stu*)b;
24     //        
25     return c.score-d.score;
26 }
27 main(){
28     int n;
29     stu sz[100];
30     scanf("%d",&n);
31     for(int i=0;i){
32         scanf("%s %s %d %d",&sz[i].name,&sz[i].sex,&sz[i].age,&sz[i].score);
33     }
34     /*
35     qsort    : 
36         1         ;
37         2           ;
38         3           ,    sizeof(s[0])  ,        ; 
39         4        ,         .
40       :            ,     s[n]       s[i]   m   ,   
41                  :qsort(&s[i],m,sizeof(s[i]),cmp);
42     */
43     qsort(sz,n,sizeof(sz[0]),cmp);
44     for(int i=0;i){
45         printf("%s %s %d %d
",sz[i].name,sz[i].sex,sz[i].age,sz[i].score); 46 } 47 }

コード2:
 1 #include
 2 #include<string.h> 
 3 //    
 4 struct student
 5 {
 6     char name[20];
 7     char sex[10];
 8     int age;
 9     int score;
10 };
11 int main()
12 {
13     int n;
14     scanf("%d",&n);
15     student stu[1000];
16     for(int i=0;i)
17     {
18         scanf("%s %s %d %d",&stu[i].name,&stu[i].sex,&stu[i].age,&stu[i].score);
19     }
20     for(int i=0;i1;i++)
21     {
22         int j=i+1;
23         if(stu[i].score>stu[j].score)
24         {
25             char str[20];
26             strcpy(str,stu[i].name);
27             strcpy(stu[i].name,stu[j].name);
28             strcpy(stu[j].name,str);
29             
30             strcpy(str,stu[i].sex);
31             strcpy(stu[i].sex,stu[j].sex);
32             strcpy(stu[j].sex,str);
33             
34             int t;
35             t=stu[i].score;
36             stu[i].score=stu[j].score;
37             stu[j].score=t;
38             
39             t=stu[i].age;
40             stu[i].age=stu[j].age;
41             stu[j].age=t;
42             i=-1;//
43         }
44     }
45     for(int i=0;i)
46     {
47         printf("%s %s %d %d
",stu[i].name,stu[i].sex,stu[i].age,stu[i].score); 48 } 49 return 0; 50 }