
要求建立一链表,将in.txt中的某科各学生分数存入链表中,并求出平均分数,将此分数输出到屏幕。程序结构如下:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
FILE *in;
char ch;
int EachScore,n=0;
float total=0;
int HandleCH(FILE *in,char ch);
struct Student{
int score;
struct Student *next;
}*head,*p1,*p2;
clrscr();
head=p1=p2=(struct Student *)malloc(sizeof(struct Student));
/*打开in.txt文件,通过判断是否为文件结束,构造循环,从而逐个成绩读取通过HandleCH函数返回*/
/*将每一个成绩至于一个节点中,构造成绩链表,方法见第十一章Creatlink.c文件*/
p1=head;
printf("Each student's score is:");
while(p1!=NULL)
{
/*通过遍历链表来打印每个学生成绩,同时统计学生人数置于n,并且将成绩累加于total */
}
printf("\nThe everage score is:%f\n",total/n);
}
/*HandleCH用于读取每一行的字符并将其求和*/
int HandleCH(FILE *in,char ch)
{
int i,EachScore=0,count=0,num[200];
while(ch!='\n')
{
num[count]=ch-48; /*0的ASCII是48*/
count++;
ch=fgetc(in);
}
for(i=0;i<count;i++)
{
EachScore+=num[i]*pow(10,count-1-i);
}
return EachScore;
}

