• 题目 1051: [编程入门]结构体之成绩统计2


    问题描述:

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

    样例输入:

    2
    1 blue 90 80 70
    b clan 80 70 60

    样例输出:

    85 75 65
    1 blue 90 80 70

    问题分析:

    使用 int 类型存储平均分,导致结果会被截断为整数,而不是保留小数部分。应该使用 float 或 double 类型来保留小数。

    代码分析:

    此处是对代码的分析:

    结构体定义:

    定义了一个名为 Student 的结构体,包含学生的学号、姓名和三门课程的成绩。

    函数定义:

    input(struct Student *student):用于输入一个学生的数据记录,通过指针传递一个 Student 结构体的地址,然后从标准输入中读取学生的学号、姓名以及三门课程的成绩。

    print(struct Student student[], int N):用于打印一个学生的数据记录,通过传入一个学生数组和学生数量,计算出平均成绩最高的学生并打印其学号、姓名以及三门课程的成绩。

    print2(struct Student student[], int N):用于打印所有学生某一门课程的平均成绩,通过传入学生数组和学生数量,计算出每门课程的平均成绩并打印。

    主函数 main():

    首先读取一个整数 N,表示学生的数量,声明了一个长度为 N 的学生数组 students,使用循环调用 input() 函数输入 N 条学生数据记录,调用 print2() 函数打印所有学生的平均成绩,调用 print() 函数打印平均成绩最高的学生的数据记录。

    代码实现:

    1. #include
    2. // 结构体定义:学生数据记录
    3. struct Student {
    4. char id[20]; // 学号
    5. char name[50]; // 姓名
    6. float score1; // 第一科成绩
    7. float score2; // 第二科成绩
    8. float score3; // 第三科成绩
    9. };
    10. // 函数:输入一个学生的数据记录
    11. void input(struct Student *student) {
    12. scanf("%s %s %f %f %f", student->id, student->name, &student->score1, &student->score2, &student->score3);
    13. }
    14. // 函数:打印一个学生的数据记录
    15. void print(struct Student student[], int N) {
    16. int score0 = (student[0].score1 + student[0].score2 + student[0].score3) / 3;
    17. int score1 = score0; // 初始化最高分为第一个学生的平均分
    18. int n = 0; // 记录最高分的学生索引
    19. for (int i = 0; i < N; i++) {
    20. int score = (student[i].score1 + student[i].score2 + student[i].score3) / 3;
    21. if (score1 <= score) {
    22. score1 = score;
    23. n = i;
    24. }
    25. }
    26. printf("%s %s %.0f %.0f %.0f\n", student[n].id, student[n].name, student[n].score1, student[n].score2, student[n].score3);
    27. }
    28. void print2(struct Student student[], int N) {
    29. int ascore1 =0;
    30. int ascore2 = 0;
    31. int ascore3=0;
    32. for (int i = 0; i < N; i++) {
    33. ascore1 += student[i].score1;
    34. ascore2 += student[i].score2;
    35. ascore3 += student[i].score3;
    36. }
    37. printf("%d %d %d\n",ascore1/N,ascore2/N,ascore3/N);
    38. }
    39. int main() {
    40. int N;
    41. scanf("%d", &N);
    42. // 声明一个学生数组,用来存储 N 条学生数据记录
    43. struct Student students[N];
    44. // 输入 N 条学生数据记录
    45. for (int i = 0; i < N; i++) {
    46. input(&students[i]); // 调用输入函数,传入当前学生的地址
    47. }
    48. print2(students, N);
    49. // 输出 N 条学生数据记录
    50. print(students, N); // 调用输出函数,传入学生数组和学生数量
    51. return 0;
    52. }

  • 相关阅读:
    WuThreat身份安全云-TVD每日漏洞情报-2023-10-16
    详解容灾架构中的脑裂问题
    记录--vue3实现excel文件预览和打印
    Spring Boot中的JDK 线程池以及Tomcat线程池使用与配置
    YOLOv7训练自己的数据集(超详细)
    什么是族?全面带你了解Revit族基本知识
    【重识云原生】第四章云网络4.7.8节——SR-IOV方案
    自动驾驶的法律和伦理问题
    Day9力扣打卡
    2020-java中级面试题
  • 原文地址:https://blog.csdn.net/m0_65537508/article/details/136359071