C语言实战开发篇-7 结构体

2019-12-18  本文已影响0人  MRJMORIARTY

结构体

1.为什么需要结构体
int float char等基本数据类型只能存单个数据
int num[],运用数组只能存同类型数据
而结构体类型可以保存多种数据。
2.结构体的定义

#include<stdio.h>
struct studentinfo{
    unsigned int num;
    char name[20];
    char sex[5];
    unsigned int age;
    double score;
    char address[20];   
};

3.定义结构体变量

#include<stdio.h>
struct studentinfo{
    unsigned int num;
    char name[20];
    char sex[5];
    unsigned int age;
    double score;
    char address[20];   
};
studentinfo stu1,stu2;

4.结构体变量的访问
“.”运算符或“->”结构体指针运算符

#include<stdio.h>
struct studentinfo{
    unsigned int num;
    char name[20];
    char sex[5];
    unsigned int age;
    double score;
    char address[20];   
} stu1, *p=&stu1;
stu1.age=18;
p->num=222018;

结构体练习,实现按成绩降序输出

#include<stdio.h>
#include<iomanip>
struct studentinfo{
    unsigned int num;
    char name[20];
    char sex[5];
    unsigned int age;
    double score;
    char address[20];
    
}; 
studentinfo stu [3]={//定义结构体数组
    {222018,"qwe","man",19,99.5,"sc"},
    {222019,"wer","wom",20,98.5,"zg"},
    {222020,"ert","man",21,99,"sc"}
};
studentinfo *p=stu;
void fun(){
    printf("学 号|姓 名|性 别|年 龄|成 绩|地 址\n"); 
} 
int main()
{
    studentinfo temp;//定义结构体变量temp 
    for(int i=0;i<3;i++){//冒泡排序 
    for(int j=0;j<3-i-1;j++){
    if((*(p+j)).score<(*(p+j+1)).score){
    temp=*(p+j+1);//在结构体里面交换,必须要用结构体变量 
    *(p+j+1)=*(p+j);
     *(p+j)=temp;
    }
    }
    }
    fun(); 
    for(int i=0;i<3;i++){
        printf("%d ",stu[i].num);
        printf("%s ",stu[i].name);
        printf("%s ",stu[i].sex);
        printf("%d ",stu[i].age);
        printf("%fd ",stu[i].score);
        printf("%s\n",stu[i].address);
    }//输出结果从大到小排列
return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读