結構體練習(C)

結構體存儲學生學號、姓名、總分,動態內存分配增長信息,而後排序windows

 1 # include <stdio.h>
 2 # include <malloc.h>
 3 //# include <windows.h>
 4 
 5 struct stu
 6 {
 7     char stuno[5]; //學號
 8     char sname[10]; //姓名
 9     int score; //總分
10 };
11 
12 int main(void)
13 {
14     int n, i, j;
15     struct stu *stuinf, temp;
16     printf("請輸入學生個數:");
17     scanf("%d", &n);
18     printf("\n");
19     stuinf = (struct stu *)malloc(sizeof(struct stu) * n);
20     //輸入
21     for (i=0; i<n; i++)
22     {
23         printf("請輸入第%d個學生信息:\n", i+1);
24         printf("請輸入學號:");
25         scanf("%s", stuinf[i].stuno);
26         printf("請輸入姓名:");
27         scanf("%s", stuinf[i].sname);
28         printf("請輸入總分:");
29         scanf("%d", &stuinf[i].score);
30         printf("\n");
31     }
32     //排序前輸出
33     printf("----------排序前:----------\n");
34     for (i=0; i<n; i++)
35     {
36         printf("第%d個學生信息:\n", i+1);
37         printf("學號:");
38         printf("%s\n", stuinf[i].stuno);
39         printf("姓名:%s\n", stuinf[i].sname);
40         printf("總分:%d\n", stuinf[i].score);
41         printf("\n");        
42     }
43     //排序
44     for (i=0; i<n-1; i++)
45     {
46         for (j=0; j<n-1-i; j++)
47         {
48             if (stuinf[j].score > stuinf[j+1].score)
49             {
50                 temp = stuinf[j];
51                 stuinf[j] = stuinf[j+1];
52                 stuinf[j+1] = temp;
53             }
54         }
55     }
56 
57 
58     //排序後輸出
59     printf("----------排序後:----------\n");
60     for (i=0; i<n; i++)
61     {
62         printf("第%d個學生信息:\n", i+1);
63         printf("學號:");
64         printf("%s\n", stuinf[i].stuno);
65         printf("姓名:%s\n", stuinf[i].sname);
66         printf("總分:%d\n", stuinf[i].score);
67         printf("\n");        
68     }
69     //system("pause");    
70     
71     return 0;        
72 }
相關文章
相關標籤/搜索