題目需求
- 原價:每件
price。
- ≤20 件:原價。
- 21~50 件:8 折 (
price * 0.8)。
- >50 件:5 折 (
price * 0.5)。
- 三位顧客分別屬三種價格區間,輸出總銷售件數與總金額。
完整程式碼
#include
int main() {
int price, q1, q2, q3;
printf("輸入單價及三位顧客購買數量 (空格隔開): ");
if (scanf("%d %d %d %d", &price, &q1, &q2, &q3) != 4) return 1;
// 區間驗證
if (!(q1 <= 20 && q2 > 20 && q2 <= 50 && q3 > 50)) {
printf("輸入數量不符合題目區間要求\n");
return 1;
}
double total = q1 * price
+ q2 * price * 0.8
+ q3 * price * 0.5;
int total_qty = q1 + q2 + q3;
printf("售出 %d 件衣服\n共 %.2f 元\n", total_qty, total);
return 0;
}
關鍵點
- 用
double 儲存金額避免整數截斷 (如 8 折產生小數)。
- 輸入驗證:確保三顧客確實落在三個不同區間。
- 格式化輸出
%.2f 顯示兩位小數 (分)。
擴展:通用分級定價函數
double calc_price(int qty, int price) {
if (qty <= 20) return qty * price;
if (qty <= 50) return qty * price * 0.8;
return qty * price * 0.5;
}