C语言中结构体和共用体实例教程

目录一、实验目的二、实验内容三、实验记录3.1 候选人选票统计3.2 print函数3.3 链表总结

一、实验目的 掌握结构体类型变量的定义和使用; 掌握结构体类型数组的概念和应用; 掌握链表的概念,初步学会对链表进行操作; 掌握共用体的概念与使用; 掌握指向结构体变量的指针。 掌握指向结构体数组的指针的应用。

二、实验内容

编写下列程序,然后上机调试运行。

    对候选人得票的统计程序。设有3个候选人,每次输入一个得票的候选人的名字,要求最后输出各人得票结果。 编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据记录,每个记录包括num、name、score[3],用主函数输入这些记录,用print函数输出这些记录。 建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。(选作)

三、实验记录

3.1 候选人选票统计

(1)源代码

# include <stdio.h>typedef struct node{char name;int cnt;}candt;int main(void){candt A,B,C;char vote;A.name='A',A.cnt=0;B.name='B',B.cnt=0;C.name='C',C.cnt=0;while(vote!='#')/*当输入为#时,表示投票结束。*/{printf("Please enter the candidate:\n");scanf("%c",&vote);getchar();switch(vote){case 'A':A.cnt++;break;case 'B':B.cnt++;break;case 'C':C.cnt++;break;default:printf("Input error!\n");}}printf("A'note:%d\n",A.cnt);printf("B'note:%d\n",B.cnt);printf("C'note:%d\n",C.cnt);return 0;}

(2)运行结果截图

3.2 print函数

(一)源代码

# include <stdio.h># define N 5struct student{char num[6];char name[10];int score[4];}stu[N];void print(struct student stu[6]);int main(void){int i,j;for(i=0;i<N;i++){printf("\nInput data of student:\n");printf("NO.: ");scanf("%s",stu[i].num);printf("name: ");scanf("%s",stu[i].name);for(j=0;j<3;j++){printf("score %d:",j+1);scanf("%d",&stu[i].score[j]);}}print(stu);return 0;}void print(struct student stu[6]){int i,j;printf(" NO.      name    score1    score2    score3\n");for(i=0;i<N;i++){printf("%5s%10s",stu[i].num,stu[i].name);for(j=0;j<3;j++)printf("%9d",stu[i].score[j]);printf("\n");}}

(2)运行结果截图

3.3 链表

(1)源代码

# include <stdio.h># include <malloc.h>//定义了一个链表节点的数据类型struct student{char num[10];char name[6];char sex[2];int age;//数据域struct student *next; //指针域}stu[10];int main(void){struct student *p,*pt,*head;int i,length,iage,flag=1;int find=0;while(flag==1){printf("Please enter the length of the list(<10):");scanf("%d",&length);if(length<10)flag=0;}//建立链表for(i=0;i<length;i++){p=(struct student *)malloc(sizeof(struct student));if(i==0)head=pt=p;elsept->next=p;pt=p;printf("NO.:");scanf("%s",&p->num);printf("name:");scanf("%s",&p->name);printf("sex:");scanf("%s",&p->sex);printf("age:");scanf("%d",&p->age);}p->next=NULL;p=head;printf("\nNO.     name    sex   age\n");while(p!=NULL){printf("%4s%8s%6s%6d\n",p->num,p->name,p->sex,p->age);p=p->next;}//删除结点printf("Input age:");scanf("%d",&iage);pt=head;p=pt;if(pt->age==iage)/*链头是待删元素*/{p=pt->next;head=pt=p;find=1;}else/*链头不是待删元素*/pt=pt->next;while(pt!=NULL){if(pt->age==iage){p->next=pt->next;find=1;}elsep=pt;pt=pt->next;}if(!find)printf("Not found%d.\n",iage);p=head;printf("\nNO.     name    sex    age\n");while(p!=NULL){printf("%4s%8s",p->num,p->name);printf("%6s%6d\n",p->sex,p->age);p=p->next;}return 0;}

(2)运行结果截图

总结

到此这篇关于C语言中结构体和共用体的文章就介绍到这了,更多相关C语言结构体和共用体内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

不敢接受失败的人,往往是那些追求完美的人,

C语言中结构体和共用体实例教程

相关文章:

你感兴趣的文章:

标签云: