第9回 (7/1) 演習の解答例

Problem 1

#include <stdio.h>

#define MAX_N 100

int main(void)
{
    struct PERSON
    {
        char family_name[20];
        char given_name[20];
        int age;
        float height;
        float weight;
    } p[MAX_N];
    int i, N;
    float age=0, height=0, weight=0;

    scanf("%d", &N);
    for (i=0; i<N; i++)
    {
        scanf("%s", p[i].given_name);
        scanf("%s", p[i].family_name);
        scanf("%d", &p[i].age);
        scanf("%f", &p[i].height);
        scanf("%f", &p[i].weight);
    }

    for (i=0; i<N; i++)
    {
        age += p[i].age;
        height += p[i].height;
        weight += p[i].weight;
    }

    printf("%f %f %f\n", age/N, height/N, weight/N);

    return 0;
}

Problem 2

#include <stdio.h>

#define MAX_N 100

int main(int argc, char *argv[])
{
    struct PERSON
    {
        char family_name[20];
        char given_name[20];
        int age;
        float height;
        float weight;
    } p[MAX_N];
    int i, N;
    float age=0, height=0, weight=0;
    FILE *fp;

    fp = fopen(argv[1], "r");
    fscanf(fp, "%d", &N);
    for (i=0; i<N; i++)
    {
        fscanf(fp, "%s", p[i].given_name);
        fscanf(fp, "%s", p[i].family_name);
        fscanf(fp, "%d", &p[i].age);
        fscanf(fp, "%f", &p[i].height);
        fscanf(fp, "%f", &p[i].weight);
    }
    fclose(fp);

    for (i=0; i<N; i++)
    {
        age += p[i].age;
        height += p[i].height;
        weight += p[i].weight;
    }

    fp = fopen(argv[2], "w");
    fprintf(fp, "%f %f %f\n", age/N, height/N, weight/N);
    fclose(fp);

    return 0;
}

Updated: