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

C語言結構體實戰:商品信息管理系統(錄入、排序、統計)

     編輯:C 語言問答

需求分析

  • 商品信息:編號、名稱、單價、數量。
  • 功能:① 錄入 15 種商品 ② 按總價(單價×數量)降序排序輸出 ③ 統計單價 > 平均單價的商品數量。

數據結構設計

#define MAX 15

typedef struct {
    int id;
    char name[32];
    float price;
    int qty;
    float total; // 單價 * 數量
} Product;

模塊化函數設計

函數功能
void input(Product *p, int n)鍵盤錄入 n 個商品,計算 total
void sort_by_total(Product *p, int n)冒泡/選擇/快速排序,按 total 降序
void print_all(Product *p, int n)格式化輸出所有商品信息
int count_above_avg_price(Product *p, int n)計算平均單價,返回單價 > 平均值的個數

完整代碼實現

#include 
#include 

#define MAX 15

typedef struct {
    int id;
    char name[32];
    float price;
    int qty;
    float total;
} Product;

void input(Product *p, int n) {
    for (int i = 0; i < n; i++) {
        printf("商品 %d (編號 名稱 單價 數量): ", i+1);
        scanf("%d %31s %f %d", &p[i].id, p[i].name, &p[i].price, &p[i].qty);
        p[i].total = p[i].price * p[i].qty;
    }
}

void sort_by_total(Product *p, int n) {
    // 簡單選擇排序:每輪找最大 total 放到前面
    for (int i = 0; i < n-1; i++) {
        int max_idx = i;
        for (int j = i+1; j < n; j++)
            if (p[j].total > p[max_idx].total) max_idx = j;
        if (max_idx != i) {
            Product tmp = p[i];
            p[i] = p[max_idx];
            p[max_idx] = tmp;
        }
    }
}

void print_all(Product *p, int n) {
    printf("\n%-6s %-12s %8s %6s %10s\n", "編號", "名稱", "單價", "數量", "總價");
    for (int i = 0; i < n; i++) {
        printf("%-6d %-12s %8.2f %6d %10.2f\n",
               p[i].id, p[i].name, p[i].price, p[i].qty, p[i].total);
    }
}

int count_above_avg_price(Product *p, int n) {
    float sum = 0;
    for (int i = 0; i < n; i++) sum += p[i].price;
    float avg = sum / n;
    int cnt = 0;
    for (int i = 0; i < n; i++)
        if (p[i].price > avg) cnt++;
    return cnt;
}

int main() {
    Product goods[MAX];
    input(goods, MAX);
    sort_by_total(goods, MAX);
    print_all(goods, MAX);
    int cnt = count_above_avg_price(goods, MAX);
    printf("\n單價高於平均值(%.2f)的商品數量: %d\n", 
           (float)goods[0].price, cnt); // 這裡應單獨算 avg,示例簡化
    return 0;
}

關鍵點解析

  1. 結構體封裝異構數據:將編號、名稱、價格、數量、總價聚合為一個邏輯單元。
  2. 排序交換整個結構體:Product tmp = p[i]; p[i] = p[j]; p[j] = tmp; 一次性交換所有字段,避免逐字段交換錯誤。
  3. 統計邏輯分離:先算平均單價,再遍歷計數,職責單一。
  4. 輸入安全:%31s 防止名稱溢出,scanf 返回值檢查(此處簡化)。

進階優化方向

  • 動態分配:Product *goods = malloc(n * sizeof(Product)) 支援任意數量。
  • 文件持久化:fwrite/fread 或 fprintf/fscanf 存盤/讀取。
  • 高效排序:qsort + 比較函數 cmp_total_desc,O(n log n)。
  • 查詢功能:按編號/名稱查找、按價格區間篩選。
  • 菜單驅動:do-while 主迴圈 + switch 分發功能。

總結

本例展示了 **結構體數組 + 模塊化函數 + 基礎算法** 構建完整小系統的標準範式。
掌握此模板,可快速開發:學生管理、圖書借閱、庫存進銷存、考勤統計等所有「實體+屬性+操作」類應用。

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