给萌新们关于C语言的讲课(结构体)

来源:互联网 发布:安卓机顶盒软件 编辑:程序博客网 时间:2024/06/05 07:58
本节学习内容:1、结构体的使用。2、结构数组的使用。
在实际问题中,经常需要将一组不同类型的数据作为一个整体来进行处理。
如对学生信息的管理:
学生的名字、性别、年龄、考试成绩等数据与某一学生紧密联系,不应该分开处理,
但这些数据类型用目前学过的数据类型不能很好的处理(既用到int,又用到chat)。

那么现在就学习一下结构体的使用。

1、结构体主要用来处理联系紧密但数据类型不一致的数据

2、结构体一般定义为全局变量,定义时应在主函数main之前。

结构体的定义:

struct student{ //这里的student是指这个新建立结构体的名字,如同int、chat一样是一种结构的名字    char name[20];  //这里大括号中的内容就是这个结构体中集合了哪些类型标识符(如int,chat)在结构体中。    int age,score;}; //注意这个分号是不能省略的

这个新的结构体的地位是和数据类型int,chat是一样的,可以用来定义一个新的变量.
 访问结构体成员的形式为[结构体变量名.成员名](对于student这个结构体的成员名有name[],age,score])
 例如

student stu1; strcpy(stu1.name, "kexie"); stu1.age=20; stu1.score=100; printf("%d\n",stu1.score);

结构体的简单使用(完整代码

#include <stdio.h>#include <string.h>struct student{ //这里的student是指这个新建立结构体的名字,如同int、chat一样是一种结构的名字    char name[20];  //这里大括号中的内容就是这个结构体中集合了哪些类型标识符(如int,chat)在结构体中。    int age,score;};int main(){    student stu1;    strcpy(stu1.name, "kexie"); //strcpy函数包含在string.h的头文件中,变量传入2个字符串,是把右边的字符串赋值给左边    stu1.age=20;    stu1.score=100;    printf("%d\n",stu1.score);    printf("请输入大学霸kexie的最新成绩:\n");    scanf("%d",&stu1.score);    printf("目前的信息为名字: %s  年龄: %d 成绩: %d \n",stu1.name,stu1.age,stu1.score);    return 0;}



上面已经有提到自己新定义结构体和int、chat等数据类型是同级的,那么这个结构体也可以定义一个数组。

那么这个数组中所有成员就都是这个结构体类型了。
将这个数组中的成员按照成绩分数从高到低排个序(完整代码

#include <stdio.h>#include <algorithm>#include<string.h>using namespace std;struct student{    char name[20];    int age,score;};// 结构体的定义方法与之前相同。student stu[10];// 不过定义的不是一个简单的变量了,而是一个数组.int cmp1(student a,student b){    return a.score>b.score;}int main(){    strcpy(stu[0].name,"me");    stu[0].age=18;    stu[0].score=90;    strcpy(stu[1].name,"buzhang");    stu[1].age=30;    stu[1].score=5;    strcpy(stu[2].name,"kexie");    stu[2].age=20;    stu[2].score=100;    int i;    for(i=0;i<3;i++)    printf("目前第 %d 位小伙伴的名字是: %s 年龄: %d 分数: %d \n",i+1,stu[i].name,stu[i].age,stu[i].score);    sort(stu,stu+3,cmp1);// 一个包含在algorithm头文件中的排序函数。    printf("经过排序后\n");    for(i=0;i<3;i++)    printf("目前第 %d 位小伙伴的名字是: %s 年龄: %d 分数: %d \n",i+1,stu[i].name,stu[i].age,stu[i].score);}