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

C 語言修改學生成績:變數賦值、結構體設計與資料持久化

     編輯:C 語言問答

基本賦值語句

float score;      // 宣告單精度浮點數變數
score = 95.5f;    // 直接賦值
score = new_val;  // 變數間賦值

結構體封裝(推薦做法)

typedef struct {
    char id[20];
    char name[50];
    float scores[5];  // 多門課程成績
    float gpa;
} Student;

// 修改某科成績
void update_score(Student *stu, int course_idx, float new_score) {
    if (course_idx >= 0 && course_idx < 5) {
        stu->scores[course_idx] = new_score;
        // 重新計算 GPA...
    }
}

進階建議

  • 靜態/全域變數:僅適用於極簡單單檔案程式,不利於模組化與執行緒安全。
  • 動態記憶體:`Student *stu = malloc(sizeof(Student));` 運行期分配,用完 `free(stu);`,適合人數不定場景。
  • 檔案持久化:二進位 `fwrite/fread` 或文本 `fprintf/fscanf` 將結構體陣列存入磁碟,實現跨程式運行保存。
  • 資料庫:SQLite 輕量嵌入式,支援 SQL 查詢修改,避免手寫檔案解析邏輯。

常見錯誤

  1. 未檢查陣列越界直接寫入 `scores[index]`。
  2. 結構體指針未初始化即解引用導致崩潰。
  3. 浮點數比較用 `==`,應用 `fabs(a-b) < EPS`。
  4. 輸入緩衝區殘留換行符導致 `scanf` 讀取異常,需清理緩衝區。

最小可行程式骨架

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STU 100
#define MAX_COURSE 5

typedef struct { ... } Student;

Student students[MAX_STU];
int count = 0;

void load_data() { ... }
void save_data() { ... }
void modify_score() { ... }

int main() {
    load_data();
    // 選單迴圈...
    save_data();
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved