70,020
社区成员




#include <stdio.h>
#include <stdlib.h>
#define N 2
#define M 2
struct student
{
int ID;
char name[20];
float score[M];
float ave;
}stu[N];
void main()
{
FILE *fp=NULL;
int i,j;
char ch;
float sum=0.0;
fp=fopen("stud.txt","wb");
if(fp==NULL)
{
printf("Cannot open this file\n");
exit (0);
}
for(i=0;i<N;i++)
{
sum=0.0; //加上这句就ok
printf("Please Enter %dth student's Name ID Scores of %dTh is :\n",i+1,M);
scanf("%s %d", stu[i].name, &stu[i].ID); //从键盘输入名字和ID时中间用空格分开;
for(j=0;j<M;j++)
{
scanf("%f",&stu[i].score[j]);
sum+=stu[i].score[j];
}
ch=getchar();
stu[i].ave=sum/M;
fwrite(&stu[i],sizeof(struct student),1,fp);
}
fclose(fp);
fp=fopen("stud.txt","rb");
if(fp==NULL)
{
printf("Cannot open this file\n");
exit (0);
}
for(i=0;i<N;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%-10d %-10s ",stu[i].ID,stu[i].name);
for(j=0;j<M;j++)
{
printf("%6.2f",stu[i].score[j]);
}
printf("%6.2f\n",stu[i].ave);
}
fclose(fp);
}
#include <stdio.h>
#include <stdlib.h>
#define N 5 //5名同学
#define M 3 //改为3,三个课程
struct student
{
int ID;
char name[20];
float score[M];
float ave;
}stu[N];
void main()
{
FILE *fp=NULL;
int i,j;
char ch;
float sum=0.0;
fp=fopen("stud.txt","wb");
if(fp==NULL)
{
printf("Cannot open this file\n");
exit (0);
}
printf("Enter like this:a1 1 78 76 87 \n");//这样的提示是需要的
for(i=0;i <N;i++)
{
printf("Please Enter %dth student's Name ID Scores of %dTh is :\n",i+1,M);
scanf("%s %d ",stu[i].name,&stu[i].ID);
for(j=0;j <M;j++)
{
scanf("%f",&stu[i].score[j]);
sum+=stu[i].score[j];
}
ch=getchar();
stu[i].ave=sum/M;/**/
sum=0; //此处总和应该清零,以计算下一个同学的平均成绩
fwrite(&stu[i],sizeof(struct student),1,fp);
}
fclose(fp);
fp=fopen("stud.txt","rb");
if(fp==NULL)
{
printf("Cannot open this file\n");
exit (0);
}
for(i=0;i <N;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
printf("%-10d %-10s ",stu[i].ID,stu[i].name);
for(j=0;j <M;j++)
{
printf("%6.2f",stu[i].score[j]);
}
printf("%6.2f\n",stu[i].ave);
}
fclose(fp);
}