习题 9.5 有10个学生,每个学生的数据包括学号、姓名、3门课程的成绩,从键盘输入10个学生数据,要求输出3门课程总平均成绩,以及最高分的学生的数据(包括学号、姓名、3门课程成绩、平均分数)。

C程序设计(第四版) 谭浩强 习题9.5 个人设计

习题 9.5 有10个学生,每个学生的数据包括学号、姓名、3门课程的成绩,从键盘输入10个学生数据,要求输出3门课程总平均成绩,以及最高分的学生的数据(包括学号、姓名、3门课程成绩、平均分数)。

代码块:

方法1:

#include 
struct student
{
    int num;
    char name[10];
    float score[3];
    float aver;
} stu[10];
void input(struct student s[], int n);
void average(struct student s[], int n);
void high_score(struct student s[], int n);
int main()
{
    input(stu, 10);
    average(stu, 10);
    high_score(stu, 10);
    return 0;
}
void input(struct student s[], int n)
{
    int i, j;
    for (i=0; iprintf("Please enter No.%d student num name score: ", i+1);
        scanf("%d %s", &s[i].num, s[i].name);
        for (j=0; j<3; scanf("%f", &s[i].score[j++]));
    }
}
void average(struct student s[], int n)
{
    int i, j;
    float sum;
    for (i=0, sum=0.0; ifor (j=0; j<3; sum+=s[i].score[j++]);
    printf("Average=%.2f\n", sum/n);
}
void high_score(struct student s[], int n)
{
    int i, j;
    float sum;
    struct student temp;
    for (i=0; ifor (j=0, sum=0.0; j<3; sum+=s[i].score[j++]);
        s[i].aver=sum/3;
    }
    for (i=0; ifor (j=i+1; jprintf("The highest student info: %d %-5s ", s[0].num, s[0].name);
    for (i=0; i<3; printf("%.2f ", s[0].score[i++]));
    printf("%.2f\n", s[0].aver);
}

方法2:

#include 
#include 
struct Student{
    int num; 
    char name[20];
    float score[3];
};
void input(Student *st);
void print(Student *st);
int main()
{
    Student *stu=(Student*)malloc(3*sizeof(Student));
    input(stu);
    print(stu);
    system("pause");
    return 0;
}
void input(Student *st)
{
    int i;
    Student *p;
    for (p=st, i=0; p3; p++, i++){
        printf("Please enter No.%d student info: ", i+1);
        scanf("%d %s", &p->num, p->name);
        for (i=0; i<3; scanf("%f", &p->score[i++]));
    }
}
void print(Student *st)
{
    int i, j;
    float aver, sum[3], total, max;
    Student *p;
    for (p=st, i=0, total=0; p3; p++, i++){
        for (j=0, sum[i]=0; j<3; sum[i]+=p->score[j++]);
        total+=sum[i]/3;
    }
    aver=total/3;
    printf("Total Average: %.2f\n", aver);
    for (i=0, max=sum[i]; i<3; i++)
        if (sum[i]>max){
            max=sum[i];
            j=i;
        }
    printf("The highest score student info: %d %s ", (st+j)->num, (st+j)->name);
    for (i=0; i<3; printf("%.2f ", (st+j)->score[i++]));
    printf("\n");
}

你可能感兴趣的:(C程序设计,(第四版),谭浩强,课后答案)