C language score analysis

The C language scores of a certain class (number of people <50) are stored in the scores.txt file. Write a program to read the students' scores from the file, and then write a function to sort the scores (do you need to indicate that library functions cannot be used)? And output the median score (for odd numbers, take the middle number, and for even numbers, take the average of the two middle numbers), average score, highest score, and lowest score.
Data format in the file:
56.0 86.5 78.0 99.0 88.0 68.5...
Output format:
The median score of this C language score is: 84.5, the average score: 80.3, the highest score: 100.0, the lowest score: 45.0.

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

void sort(int a[], int size);

int main()
{
    
    
    FILE *fp;
    float scores[50], sum=0, avg, med; //存储成绩
    int pnum=0; //人数

    if((fp = fopen("./scores.txt", "r")) == NULL) //打开文件
    {
    
    
        printf("cannot open file\n");
        return 1;
    }

    while(1) //读取成绩和人数
    {
    
    
        fscanf(fp, "%f", &scores[pnum]);
        pnum++;
        if (feof(fp)) break;
    }

    sort(scores,pnum); //排序

    for(int loop = 0; loop < pnum; loop++) //求平均分
    {
    
    
        sum = sum + scores[loop];
    }

    avg = sum / pnum;

    if (pnum%2==0) med = (scores[pnum/2-1]+scores[pnum/2])/2;
    else med = scores[pnum/2];

    printf("本次C语言成绩的中位数为:%.1f,平均分:%.1f,最高分:%.1f,最低分:%.1f。", med, avg, scores[pnum-1], scores[0]);

    return 0;

}

/*
void sort(int a[], int size) //冒泡排序
{
    int i, j, tmp, flag;
    for(i=1; i<size; ++i)
      {
        flag = 0;   //标记变量赋值为0
        for (j = 0; j < size-i; ++j)
            if (a[j]> a[j+1])
            {
               tmp = a[j];
               a[j] = a[j+1];
               a[j+1] = tmp;
               flag = 1;
            }//有交换,flag设为1
           if (!flag) break;
      }

}
*/

void sort(int a[], int size) //直接选择排序
{
    
    
   int lh, minh, k, tmp;
   for (lh = 0; lh < size-1; ++lh)
    {
    
    
       //找从lh到size-1之间的最小值
       minh = lh;
       for (k = lh; k < size; ++k)
            if ( a[k] < a[minh] )   minh = k;
       //将最小值交换到前面
        tmp = a[lh];
        a[lh] = a[minh];
        a[minh] = tmp;      }
}

Guess you like

Origin blog.csdn.net/weixin_42145554/article/details/129255284