從文件中讀取學生成績並輸出 C語言

題目

設存儲在D盤根目錄下的文本文件score.dat中記錄着學生的姓名和成績,每一行表示一個學生的信息,包括學生姓名(姓名中不存在空格等特殊符號)和成績,它們之間用製表符(\t)分隔,例如:

  zhangsan  84.5
  lisi      78
  wangwu  65.5
  maliu    90

請針對該文件寫一個程序,該程序的功能是計算所有學生的平均成績,並輸出其中成績
最高的3個學生的信息(姓名和成績);若學生總人數不足3人,則輸出全部學生的信息。

拋磚引玉

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct student_type {
    char name[10];
    char scoreStr[10];
    float score;
} STU;

int main( int argc, char *argv[] )  
{
    int i=0,maxScoreList[3]={0,0,0};//用於記錄前三高分
    int maxScoreIndexList[3]={-1,-1,-1};//用於記錄高分的索引
    FILE *fp;
    STU stud[10];
    float totalScore=0;

    fp = fopen("score.dat","r");
    char ch[255],name[10],*p,*p_end;
    
    while(fgets(ch, 255, (FILE*)fp)!=NULL){

        p = strchr(ch,'\t'); //獲取製表符的位置
        p_end = strchr(ch,'\n');

        for(int k=0;k<p-ch;k++){
            stud[i].name[k] = ch[k];
        }

        for(int j=0;j<p_end-p;j++){
            stud[i].scoreStr[j] = ch[p-ch+1+j];
        }

        stud[i].score = atof(stud[i].scoreStr);

        totalScore=totalScore+stud[i].score;
        // printf("totalScore is %f\n",totalScore);

        if(stud[i].score>maxScoreList[0]){
            maxScoreList[2]=maxScoreList[1];
            maxScoreList[1]=maxScoreList[0];
            maxScoreList[0]=stud[i].score;

            maxScoreIndexList[2]=maxScoreIndexList[1];
            maxScoreIndexList[1]=maxScoreIndexList[0];
            maxScoreIndexList[0]=i;
        }else if(stud[i].score>maxScoreList[1]){
            maxScoreList[2]=maxScoreList[1];
            maxScoreList[1]=stud[i].score;

            maxScoreIndexList[2]=maxScoreIndexList[1];
            maxScoreIndexList[1]=i;
        }else if(stud[i].score>maxScoreList[2]){
            maxScoreList[2]=stud[i].score;
            maxScoreIndexList[2]=i;
        }
        i++;
    }

    printf("the average score is %f\n",totalScore/i);
    for(int i=0;i<3;i++){
        if(maxScoreIndexList[i]>-1 && maxScoreList[i]>0){
            printf("the rank %d is %s, and his score is %f\n",i+1,stud[maxScoreIndexList[i]].name,stud[maxScoreIndexList[i]].score);
        }
    }
    return 0;
}

在這裏插入圖片描述
僅僅能實現功能,還有很大優化空間,求指點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章