c语言 13

1、

#include <stdio.h>

typedef struct{
    char name[128];
    double height;
    double weight;
}Typex;

void swap(Typex *x, Typex *y)
{
    Typex tmp = *x;
    *x = *y;
    *y = tmp;
}

void sort(Typex x[], int n)
{
    int i, j;
    for(i = 0; i < n - 1; i++)
    {
        for(j = n - 1; j > i; j--)
        {
            if(x[j - 1].height > x[j].height)
            {
                swap(&x[j - 1], &x[j]);
            }
        }
    }
}

int main(void)
{
    FILE *fp;
    
    int lines = 0;
    char name[128];
    double height, weight;
    double dsum = 0, wsum = 0;
    
    if((fp = fopen("hw.dat","r")) == NULL)
        printf("afile does not exist.");
    else
    {
        while(fscanf(fp, "%s%lf%lf", name, &height, &weight) == 3)
        {
            printf("%-8s%8.2f%8.2f
", name, height, weight);
            lines++;
            dsum += height;
            wsum += weight;    
        }
        puts("
========================
");
        printf("average: %8.2f%8.2f
", dsum/lines, wsum/lines);
        
        fp = fopen("hw.dat","r");
        
        Typex x[lines];
        int i = 0;
        while(fscanf(fp, "%s%lf%lf", x[i].name, &x[i].height, &x[i].weight) == 3)
        {
            i++;
        }
    
        sort(x, lines);
        puts("
============================
");
        for(i = 0; i < lines; i++)
            printf("%-8s%8.2f%8.2f
", x[i].name, x[i].height, x[i].weight);
        fclose(fp);
    } 
    return 0;
}

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14859351.html