2021-10-31【结构体】

自定义的可用的数据类型

结构体 struct

struct student{
	int num;
	int scores;
}stu1,stu2,stu3;

student 结构体标签

num,scores 结构体中变量的定义

stu1,stu2,stu3 结构变量

定义在结构的末尾,最后一个分号之前可以指定一个或多个结构变量。

此外:

struct{		//无结构体标签 
	int a1;
	int b1;
}s1;

struct node1{
	int a2;
	int b2;
};//无声明变量
typedef struct node{
	int a3;
	int b3;
    struct node1 abb;
    struct node *next;
}s2,*sw;
//现在可以用s2作为类型声明新的结构体变量

主函数


int main(){
    struct node1 m;
	m.a2;

    // 访问结构成员 :
    // 为了访问结构的成员,我们使用成员访问运算符(.)
    sw qew;
    qew->abb.a2;//结构体指针的成员变量访问符
    s2 q;
	q.abb.a2;

    struct node qwe;
    qwe.a3;

    struct student stu5;
	stu5.num;
	
	return 0;
} 

例如:

struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book = {"C 语言", "RUNOOB", "编程语言", 123456};
 
int main()
{
    printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
}

例题:

建立一个学生结构体数组,有三个学生元素。

结构体里有四个成员:学号,姓名,出生年月日(也是结构体变量),成绩。

编程实现这三个学生所有信息的输入,输出,并求出成绩的平均值输出。


struct birth{
	int year;
	int month;
	int day;
};
struct stu{
	int numb;
	char name[10];
	struct birth a;
	int score;
}student[5];

int main(){
	double sum=0;
	for(int i=0;i<3;i++){
		scanf("%d%s%d%d%d%d",&student[i].numb,student[i].name,&student[i].a.year,&student[i].a.month,&student[i].a.day,&student[i].score);
	}
	for(int i=0;i<3;i++){
		printf("%d %s %d %d %d %d\n",student[i].numb,student[i].name,student[i].a.year,student[i].a.month,student[i].a.day,student[i].score);
		sum+=student[i].score;
	}
	printf("成绩的平均值为:%.2lf",sum/3);
}

input:

1 zhang 1900 1 1 90
2 wang 1901 1 1 90
3 gao 1920 1 1 90

output:

1 zhang 1900 1 1 90
2 wang 1901 1 1 90
3 gao 1920 1 1 90
成绩的平均值为:90.00

结构体指针

指向结构体的指针

struct stu *pstu;

例如:

struct stu{
    int num;
    char *name;
    char sex;
    float score;
}boy1 = {006,"zhangzhang",'1',69.6};

int main() {

    struct stu *pstu;
    pstu = &boy1;

    printf("%d,%s\n", boy1.num, boy1.name);

    printf("%d,%s\n", (*pstu).num, (*pstu).name);

    printf("%d,%s\n", pstu->num, pstu->name);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eternity_GQM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值