C语言------结构体和共用体

仅供借鉴、仅供借鉴、仅供借鉴(整理了一下大一C语言每个章节的练习题、没得题目、只有程序了)

1 、实训名称

实训8:结构体和共用体

2 、实训目的及要求

1、了解结构体,共用体的概念
2、熟练掌握结构体,共用体的定义、赋值、使用。
3 、学会正确使用结构体变量

3、源代码及运行截图


#include<stdlib.h>
#include<stdio.h>
#include<String.h>
#define N 10
 
struct student{
    char name[N];
	int score;
	int no; //学号
};

void input(struct student stu[N]);//输入函数
void sort(struct student stu[N]);//排序函数
void aver(struct student stu[N]);//求分函数
void locating(struct student stu[N]);//查找函数

void input(struct student stu[N]){
	int i;
	for(i=0;i<N;i++)
	{
		printf("请输入第%d名学生的信息:",i+1);
		scanf("%s%d%d",&stu[i].name,&stu[i].no,&stu[i].score);
	}
}
void sort(struct student stu[N]){   //冒泡排序
	int i,k;
	struct student temp;
	for(k=1;k<N;k++)
		for(i=N-1;i>=k;i--)
			if(stu[i].score>stu[i-1].score)
			{
				temp=stu[i];
				stu[i]=stu[i-1];
				stu[i-1]=temp;
			}
    printf("\t排名\t姓名\t学号\t成绩\n");
	for(i=0;i<N;i++)
		{			
			printf("\t%-8d%-8s%-8d%-8d\n",i+1,stu[i].name,stu[i].no,stu[i].score);
		}
}
void aver(struct student stu[N]){
	int max=stu[0].score;
	int min=stu[0].score;
	double average;
	int i,sum=0;
	for(i=0;i<N;i++)
	{
		if(stu[i].score>max)
		{
			max=stu[i].score;
		}	 
	}
	for(i=0;i<N;i++)
	{
		if(stu[i].score<min)
		{
			min=stu[i].score;
		}	 
	}
	for(i=0;i<N;i++)
	{
		sum+=stu[i].score;
	}    
	average=sum/10.0;
	printf("这10名学生的平均分为:%.2lf,最高分为:%d,最低分为:%d",average,max,min);
}

void locating(struct student stu[N]){
	int i,ch;
	printf("请输入你要查找的学号:");
	scanf("%d",&ch);
	for(i=0;i<N;i++)
		if(ch==stu[i].no)
		{
			printf("查找到的学生,信息如下\n");
			printf("\t姓名\t学号\t成绩\n");
			printf("\t%-8s%-8d%-8d\n",stu[i].name,stu[i].no,stu[i].score);
		}
}

int main()
{
	int i;
	struct student stu[N];
	input(stu);
	printf("\n成绩经过排序后为:\n");
	sort(stu);
	printf("\n");
	locating(stu);
	printf("\n");
	aver(stu);
	getchar();
	getchar();
	return 0;
}

在这里插入图片描述

4 、小结

通过本次实验,结构体可以存储不同类型的数据。可以将一类事物的相关信息写在一个结构体中便于操作。在对结构体进行赋值时需要用到循环结构。结构体可以当做特殊的数组进行对待,基本的操作和数组相似。

posted on 2022-08-28 22:18  热爱技术的小郑  阅读(26)  评论(0编辑  收藏  举报