你的代码修改过后的:
#include"stdio.h"
#include<stdio.h>
#define N 5
struct student
{
int num;
char name[5];
int c1;
int c2;
int c3;
float avg;
};
void main()
{
struct student st[N];
int i,j,m;
printf("请分别输入这五个学生的学号、姓名以及三门课的成绩:\n");
float ar1=0,ar2=0,ar3=0,ar4=0,ar5=0;
FILE *fp;
for(i=0;i<N;i++)
{
scanf("%d",&st[i].num);
scanf("%s",st[i].name);
scanf("%d",&st[i].c1);
scanf("%d",&st[i].c2);
scanf("%d",&st[i].c3);
st[i].avg = (st[i].c1 + st[i].c2 + st[i].c3)/3.0;
}
fp=fopen("stud.txt","w");
fprintf(fp,"学号 姓名 成绩 平均分\n ");
for(m=0;m<5;m++)
{
fprintf(fp,"%d %s %d %d %d %f\n",st[m].num,st[m].name,st[m].c1,st[m].c2,st[m].c3,st[m].avg);
}
fclose(fp);
}
我按照题目写的全部代码:
运行结果示例:
写入文件内容示例:
#include<stdio.h>
#define N 5
typedef struct Student{
long long int id;
char name[20];
float chinese;
float math;
float english;
float avg;
}Student;
Student student[N];
Student student1[N];
/**控制台录入信息*/
void insert(Student student[N])
{
int i;
for(i=0;i<N;i++)
{
printf("请输入第%d位学生的信息:\n",i+1);
scanf("%lld %s %f %f %f",&student[i].id,student[i].name,&student[i].chinese,&student[i].math,&student[i].english);
student[i].avg=(student[i].chinese+student[i].math+student[i].english)/(3*1.0);
}
}
/**信息存储到stud.txt文件*/
void ctrl_s(Student student[N])
{
FILE*f;
int i;
f=fopen("stud.txt","w");
for(i=0;i<N;i++)
{
fprintf(f,"%lld\t%s\t%f\t%f\t%f\t%f\n",
student[i].id,student[i].name,student[i].chinese,student[i].math,student[i].english,student[i].avg);
}
fclose(f);
}
void print(Student student1[N])
{
FILE*f;
int i;
f=fopen("stud.txt","r");
if(f==NULL){printf("文件打开失败!\n");}
else
{
for(i=0;i<N;i++)
{
fscanf(f,"%lld\t%s\t%f\t%f\t%f\t%f\n",
&student1[i].id,student1[i].name,&student1[i].chinese,&student1[i].math,&student1[i].english,&student1[i].avg);
}
for(i=0;i<N;i++)
{
printf("学号:%lld 姓名:%s 语文:%.2f 数学:%.2f 英语:%.2f 平均分:%.2f\n",
student1[i].id,student1[i].name,student1[i].chinese,student1[i].math,student1[i].english,student1[i].avg);
}
}
fclose(f);
}
int main()
{
insert(student);
ctrl_s(student);
printf("学生信息如下:\n");
print(student1);
return 0;
}