一、实验目的及要求
- 掌握使用文件打开、关闭、读、写等文件操作函数;
- 学会用缓冲文件系统对文件进行的综合操作;
- 进一步提高程序的设计能力和调试能力;
- 要求:上机前先编制程序并画出程序框图;独立完成实验;独立完成实验报告。
2.有5个学生,每个学生有3门课的成绩,从键盘上输入以上数据,计算平均成绩,将原有的数据和计算出的平均成绩存放在磁盘文件中。
#define _CRT_SECURE_NO_WARNINGS
//2.有5个学生,每个学生有3门课的成绩,从键盘上输入以上数据,
//计算平均成绩,将原有的数据和计算出的平均成绩存放在磁盘文件中。
#include<stdio.h>
#define N 5
struct student
{
int num;
char name[20];
float score[3];
float avg;
};
float avg;
void input(struct student stu[])
{
int i;
float sum = 0;
for (i = 0; i < N; i++)
{
printf("请输入第%d个学生三门课程的成绩", i + 1);
scanf_s("%f%f%f",&stu[i].score[0], &stu[i].score[1], &stu[i].score[2]);
stu[i].avg = (stu[i].score[0] + stu[i].score[1] + stu[i].score[2]) / 3;
sum += stu[i].avg;
}
avg = sum / N;
}
void output(struct student stu[])
{
int i;
for (i = 0; i < N; i++)
{
for (i = 0; i < N; i++)
printf("平均成绩:%.2f\n", stu[i].avg);
}
}
int main()
{
struct student stu[N];
input(stu);
output(stu);
FILE* fp = fopen("D:\\大学\\大一下\\程序设计综合训练\\stu.txt", "w+");
if (!fp)
return -1;
int i;
for(i = 0; i < N; i++)
{
printf("%.2f %.2f %.2f\n", stu[i].score[0], stu[i].score[1], stu[i].score[2]);
fprintf(fp, "%.2f %.2f %.2f", stu[i].score[0], stu[i].score[1], stu[i].score[2]);
fprintf(fp, "%.2f ", stu[i].avg);
}
fclose(fp);
return 0;
}
3.将2题中的学生数据,按平均分进行排序处理,将已经排序的学生数据存入一个新文件中。
//2.有5个学生,每个学生有3门课的成绩,从键盘上输入以上数据,
//计算平均成绩,将原有的数据和计算出的平均成绩存放在磁盘文件中。
#include<stdio.h>
#define N 5
struct student
{
int num;
char name[20];
float score[3];
float avg;
};
float avg;
void input(struct student stu[])
{
int i;
float sum = 0;
for (i = 0; i < N; i++)
{
printf("请输入第%d个学生三门课程的成绩", i + 1);
scanf_s("%f%f%f", &stu[i].score[0], &stu[i].score[1], &stu[i].score[2]);
stu[i].avg = (stu[i].score[0] + stu[i].score[1] + stu[i].score[2]) / 3;
sum += stu[i].avg;
}
avg = sum / N;
}
void output(struct student stu[])
{
int i;
for (i = 0; i < N; i++)
{
printf("三门课的成绩:%.2f %.2f %.2f\n", stu[i].score[0], stu[i].score[1], stu[i].score[2]);
for (i = 0; i < N; i++)
printf("平均成绩:%.2f", stu[i].avg);
}
}
void sortavg(struct student stu[])
{
int i, j, k;
struct student temp;
for (i = 0; i < N - 1; i++)
{
k = i;
for (j = i + 1; j < N; j++)
if (stu[j].avg < stu[k].avg)
k = j;
temp = stu[i];
stu[i] = stu[k];
stu[k] = temp;
}
}
int main()
{
struct student stu[N];
input(stu);
sortavg(stu);
output(stu);
FILE* fp = fopen("stu.txt", "w+");
if (!fp)
return -1;
int i;
for (i = 0; i < N; i++)
{
printf("%f%f%f", stu[i].score[0], stu[i].score[1], stu[i].score[2]);
fprintf(fp, "%f%f%f", stu[i].score[0], stu[i].score[1], stu[i].score[2]);
}
fclose(fp);
return 0;
}