c语言 13

1、

#include <stdio.h>

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

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

void sort(Type1 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 hsum = 0, wsum = 0;
    Type1 x[6];
    
    if((fp = fopen("a.txt", "r")) == NULL)
        printf("aFile open failed.
");
    else
    {
        while(fscanf(fp, "%s%lf%lf", name, &height, &weight) == 3)
        {
            printf("%-10s %5.1f %5.1f
", name, height, weight);
            lines++;
            hsum += height;
            wsum += weight;    
        }
        puts("
================================
");
        printf("average  %5.1f %5.1f


", hsum/lines, wsum/lines);
        
        fp = fopen("a.txt", "r");
        int i = 0;
        while(fscanf(fp, "%s%lf%lf", x[i].name, &x[i].height, &x[i].weight) == 3)
        {
            i++;
        } 
        fclose(fp);
        
        sort(x, 6);
        puts("sort by height: 
");
        for(i = 0; i < 6; i++)
        {
            printf("%-10s %5.1f %5.1f
", x[i].name, x[i].height, x[i].weight);
        }
    }
    return 0;
}

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