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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/navicheung/article/details/79726889

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

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

代码块:

方法1:

#include <stdio.h>
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; i<n; i++){
        printf("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; i<n; i++)
        for (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; i<n; i++){
        for (j=0, sum=0.0; j<3; sum+=s[i].score[j++]);
        s[i].aver=sum/3;
    }
    for (i=0; i<n; i++)
        for (j=i+1; j<n; s[i].aver<s[j].aver ? temp=s[i], s[i]=s[j], s[j]=temp, j++ : j++);
    printf("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 <stdio.h>
#include <stdlib.h>
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; p<st+3; 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; p<st+3; 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");
}
展开阅读全文

没有更多推荐了,返回首页