统计学生成绩,并存储到磁盘文件中

要求:

有5个学生,每个学生有3门课成绩,从键盘输入学生数据(包括姓名,学号,3门课成绩),计算出平均成绩,将原有数据和计算出的平均分数放在磁盘文件“file1.c”中。

分析:

先定义一个结构体数组student_type stud[SIZE],SIZE=5,来存储学生成绩及相关信息。首先向结构体数组元素依次输入学生相关信息,接着利用fwrite()函数将结构体数组信息写进磁盘文件“file1.c”中,为了更好地显示输入的信息,这里增加了磁盘文件读取部分,利用fread()函数将读取到信息存储在结构体数组student_type stud1[SIZE]中,并显示在终端屏幕上。

程序如下:

#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
struct student_type{
	char name[15];  //姓名 
	int num;        //学号 
	float score[3]; //三门课成绩 
	float ave;      //平均分数 
}stud[SIZE],stud1[SIZE];

int main()
{
	FILE *fp;
	int i,j;
	float sum=0;
	if((fp=fopen("file1.c","wb"))==NULL)
	{
		printf("cannot open the file!");
		exit(0);
	}
	for(i=0;i<SIZE;i++)
	  scanf("%s%d%f%f%f",stud[i].name,&stud[i].num,&stud[i].score[0],&stud[i].score[1],&stud[i].score[2]);

	for(i=0;i<SIZE;i++)
	{
		sum=0;
		for(j=0;j<3;j++)
		  sum=sum+stud[i].score[j];
		stud[i].ave=sum/3;
	}
	for(i=0;i<SIZE;i++)
	{
		if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
		  printf("file write error!");
	}
	fclose(fp);
	
	fp=fopen("file1.c","rb");
	if(fp==NULL)
	{
		printf("cannot open the file!");
		exit(0);
	}
	printf("从file1.c文件中读取到的信息如下:\n");
	printf("姓名  学号   成绩1   成绩2   成绩2   平均分数\n");
	for(i=0;i<SIZE;i++)
	{
		fread(&stud1[i],sizeof(student_type),1,fp);
		printf("%s   %d %f %f %f %f\n",stud1[i].name,stud1[i].num,stud1[i].score[0],stud1[i].score[1],stud1[i].score[2],stud1[i].ave);
	}
	fclose(fp);
	return 0;
}
运行结果如下:




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值