首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言結構體實戰:學生成績管理系統

     編輯:C 語言問答

需求分析

輸入 3 名學生的學號、姓名、3 門課成績,計算並輸出每門課的平均分。這是結構體數組、函數模塊化、指針傳參的綜合練習。

數據結構設計

typedef struct {
    int id;           // 學號
    char name[20];    // 姓名
    float scores[3];  // 3 門課成績
    float avg;        // 個人平均分(可選)
} Student;

模塊化函數設計

函數功能參數
void input(Student *stu, int n)鍵盤錄入 n 名學生信息結構體指針、人數
void calcCourseAvg(Student *stu, int n, float *courseAvg)計算每門課平均分結構體指針、人數、輸出數組
void printReport(Student *stu, int n, float *courseAvg)格式化輸出所有數據結構體指針、人數、課程平均分

核心代碼實現

#include <stdio.h>
#define STU_NUM 3
#define COURSE_NUM 3

void input(Student *stu, int n) {
    for (int i = 0; i < n; i++) {
        printf("第 %d 位學生 (學號 姓名 三門成績): ", i+1);
        scanf("%d %19s %f %f %f", &stu[i].id, stu[i].name,
              &stu[i].scores[0], &stu[i].scores[1], &stu[i].scores[2]);
    }
}

void calcCourseAvg(Student *stu, int n, float *courseAvg) {
    for (int c = 0; c < COURSE_NUM; c++) {
        float sum = 0;
        for (int i = 0; i < n; i++) sum += stu[i].scores[c];
        courseAvg[c] = sum / n;
    }
}

void printReport(Student *stu, int n, float *courseAvg) {
    printf("\n%-10s %-10s %s %s %s %-10s\n", "學號", "姓名", "課程1", "課程2", "課程3", "個人均分");
    for (int i = 0; i < n; i++) {
        float sum = 0;
        printf("%-10d %-10s ", stu[i].id, stu[i].name);
        for (int c = 0; c < COURSE_NUM; c++) {
            printf("%-7.1f ", stu[i].scores[c]);
            sum += stu[i].scores[c];
        }
        printf("%-7.1f\n", sum / COURSE_NUM);
    }
    printf("\n各課程平均分: ");
    for (int c = 0; c < COURSE_NUM; c++) printf("課程%d: %.1f  ", c+1, courseAvg[c]);
    printf("\n");
}

int main() {
    Student class[STU_NUM];
    float courseAvg[COURSE_NUM];

    input(class, STU_NUM);
    calcCourseAvg(class, STU_NUM, courseAvg);
    printReport(class, STU_NUM, courseAvg);
    return 0;
}

進階優化方向

  • 動態人數:用 malloc 分配 Student *class,運行時輸入人數。
  • 文件持久化:添加 saveToFile/loadFromFile 實現數據存盤。
  • 排序功能:按總分/平均分排名,使用 qsort 配合比較函數。
  • 錯誤處理:檢查 scanf 返回值,防止非法輸入導致程序崩潰。

常見錯誤避坑

  1. 結構體數組退化為指針:函數參數用 Student *stu 而非 Student stu[] 更直觀。
  2. 字符串輸入溢出:%19s 限制寬度,防止覆蓋 name[20]。
  3. 浮點數精度:輸出用 %.1f 或 %.2f,避免科學計數法。
  4. 未初始化:calloc 或手動置零,防止垃圾值參與計算。

總結

本例展示了 結構體封裝異構數據、函數單一職責、指針高效傳遞 的 C 語言工程化思想。掌握此模式,可快速構建通訊錄、庫存管理、考勤系統等實用小工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved