码迷,mamicode.com
首页 > 其他好文 > 详细

struct的使用

时间:2015-08-27 21:04:53      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

编写一个学生struct,成员有学号(id)、姓名(name)、成绩(5门课程),随机生成多个学生的学号、姓名和成绩存储到结构体数组。再根据总分进行排名并输出学生的信息和总分。

 1 #ifndef STU_H
 2 #define STU_H
 3 
 4 #include<stdio.h>
 5 #include<stdlib.h>
 6 
 7 #define LEN 3//姓名长度
 8 #define NUM 5//科目数
 9 
10 typedef struct Student
11 {
12     int id;
13     char name[LEN];
14     int score[NUM];
15 }STU;
16 
17 //初始化
18 void id_init(int *val);
19 void name_init(char *name, int len);
20 void score_init(int *score, int num);
21 void initArray(STU *stuArray, int cnt);
22 
23 //打印
24 void printStu(STU stu);
25 void printArray(STU *stuArray, int cnt);
26 
27 int sum(STU stu);
28 
29 
30 #endif
 1 #include "student.h"
 2 
 3 //初始化
 4 void id_init(int *val)
 5 {
 6     *val = rand() % 1000 + 2000;
 7 }
 8 void name_init(char *name, int len)
 9 {
10     int i;
11     for(i = 0; i < len; i++)
12     {
13         if(i == 0)
14             name[i] = A + rand() % 26;
15         else
16             name[i] = a + rand() % 26;
17     }
18     name[i] = \0;
19 }
20 
21 void score_init(int *score, int num)
22 {
23     int i;
24     for(i = 0; i < num; i++)
25     {
26         score[i] = rand() % 100 + 1;
27     }
28 }
29 void initArray(STU *stuArray, int cnt)
30 {
31     int i;
32     for(i = 0; i < cnt; i++)
33     {
34         id_init(&stuArray[i].id);
35         name_init(stuArray[i].name,LEN);
36         score_init(stuArray[i].score,NUM);
37     }
38 }
39 
40 int sum(STU stu)
41 {
42     int total = 0;
43     int i;
44     for(i = 0; i < NUM; i++)
45         total += stu.score[i];
46     return total;
47 }
48 
49 //打印
50 void printStu(STU stu)
51 {
52     int i;
53     printf("%5d",stu.id);
54     printf("%5s",stu.name);
55     for(i = 0; i < NUM; i++)
56         printf("%3d",stu.score[i]);
57     printf("%4d\n",sum(stu));
58 }
59 
60 void printArray(STU *stuArray, int cnt)
61 {
62     int i;
63     for(i = 0; i < cnt; i++)
64         printStu(stuArray[i]);
65 }
 1 #include "student.h"
 2 
 3 int main()
 4 {
 5     STU stuArray[5];
 6     initArray(stuArray,5);
 7     printArray(stuArray,5);
 8     system("pause");
 9     return 0;
10 }

 

struct的使用

标签:

原文地址:http://www.cnblogs.com/cpsmile/p/4764349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!