c语言 结构体动态创建

 1 #include<stdio.h>
 2 #include<malloc.h>
 3 struct Student
 4 {
 5     int num;  //学号
 6     int total; //总分
 7     char name[20]; //姓名
 8     float score[3]; //3个课目的分数
 9 };
10 
11 int main()
12 {
13     int N,i,j;
14     printf("Please input N:");
15     scanf("%d",&N);
16     struct Student *stu = NULL;
17     stu = (struct Student*)malloc(sizeof(struct Student)*N); //创建一个结构体含有N个数据
18     for(i = 0; i < N; i++)
19     {
20         stu[i].total = 0;
21         printf("Please input the No%d student's number:",i+1);
22         scanf("%d",&stu[i].num);
23         printf("Please input the No%d student's name:",i+1);
24         scanf("%s",stu[i].name);
25         for(j = 0; j < 3; j++)
26         {
27             stu[i].score[j] = 0.0; //初始化float 老版本编译器如果不初始化可能会报错
28             printf("Please input the No%d student' score of %d:",i+1,j+1);
29             scanf("%f",&stu[i].score[j]);
30                stu[i].total = stu[i].total + (int)stu[i].score[j];  //求总分
31         }
32     }
33     for(i = 0; i < N; i++)
34     {
35         if(stu[i].total >= 240) //求总分大于240的
36         {
37             printf("%d %s\n",stu[i].num,stu[i].name);
38         }
39     }
40     for(i = 0; i < N; i++)
41     {
42         for(j = 0; j < 3; j++)
43         {
44             if(stu[i].score[j] < 60) //求科目小于60的
45             {
46                printf("%d %s %.2f\n",stu[i].num,stu[i].name,stu[i].score[j]);
47             }
48         }
49     //    printf(" %d \n",stu[i].total);
50     }
51     free(stu); //释放
52     return 0;
53 }

 

posted on 2014-12-02 12:32  嘘寒问暖  阅读(9127)  评论(0编辑  收藏  举报

导航