#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;
}
Product tmp = p[i]; p[i] = p[j]; p[j] = tmp; 一次性交換所有字段,避免逐字段交換錯誤。%31s 防止名稱溢出,scanf 返回值檢查(此處簡化)。Product *goods = malloc(n * sizeof(Product)) 支援任意數量。fwrite/fread 或 fprintf/fscanf 存盤/讀取。qsort + 比較函數 cmp_total_desc,O(n log n)。do-while 主迴圈 + switch 分發功能。本例展示了 **結構體數組 + 模塊化函數 + 基礎算法** 構建完整小系統的標準範式。
掌握此模板,可快速開發:學生管理、圖書借閱、庫存進銷存、考勤統計等所有「實體+屬性+操作」類應用。