Year 11 Cambridge Computer Science: Case Study – Vending Machine Simulation | Year 11 Cambridge 计算机:案例分析实战演练 – 自动售货机模拟

📚 Year 11 Cambridge Computer Science: Case Study – Vending Machine Simulation | Year 11 Cambridge 计算机:案例分析实战演练 – 自动售货机模拟

This case study walks you through the complete problem-solving process required in Cambridge IGCSE Computer Science. We will simulate a school vending machine that sells snacks, accepts coins and returns change. Throughout this drill, you will practise decomposition, algorithm design, test data selection and evaluation – exactly the skills examined in Paper 2.

本案例分析将带你完整经历 Cambridge IGCSE 计算机科学所要求的解题过程。我们将模拟一台售卖零食、接受硬币并找零的校园自动售货机。在整个演练中,你将练习问题分解、算法设计、测试数据选用和方案评估——这些正是 Paper 2 中考查的核心技能。

1. Problem Definition | 问题定义

The school wants a program to simulate a vending machine that sells three items: crisps (£1.20), chocolate (£0.90) and water (£0.70). A customer selects an item by entering its number (1-3). The machine only accepts coins of denominations £1, 50p, 20p, 10p and 5p. The customer inserts coins one by one until the total inserted reaches or exceeds the price. If the inserted amount is sufficient and the item is in stock, the machine dispenses the item, calculates the change due and updates the stock. If the item is out of stock or the inserted amount is insufficient, an appropriate message is displayed.

学校需要一个程序来模拟自动售货机,该机器出售三种商品:薯片(£1.20)、巧克力(£0.90)和矿泉水(£0.70)。顾客通过输入商品编号(1-3)来选择商品。售货机只接受面额为 £1、50便士、20便士、10便士和5便士的硬币。顾客一枚一枚地投入硬币,直到投入总额达到或超过售价。如果投入金额足够且商品有库存,则机器发放商品,计算找零并更新库存。若商品缺货或投入金额不足,则显示相应的提示信息。


2. Decomposition and Abstraction | 分解与抽象

We break the problem into manageable sub-tasks: display the menu and prices, get a valid item selection, check stock availability, accept coins until the total meets or exceeds the price, calculate the change using the available coin denominations, update stock and output the result. Abstraction helps us focus on the essential details: we can ignore the physical mechanism of dispensing and treat the vending machine as a collection of arrays storing item names, prices and stock levels.

我们把问题分解为若干可管理的子任务:显示菜单和价格,获取有效的商品选择,检查库存可用性,接收硬币直至总额达到或超过售价,用可用的硬币面额计算找零,更新库存并输出结果。抽象帮助我们聚焦于关键细节:我们可以忽略实际出货的物理机械,而将售货机看作储存商品名称、价格和库存水平的若干数组。


3. Inputs, Outputs and Processing | 输入、输出与处理

Inputs: item number (integer 1-3), coin values inserted one at a time (real numbers representing valid denominations). Outputs: confirmation message (‘Item dispensed’ or ‘Out of stock’ or ‘Insufficient amount’), change breakdown (how many of each coin denomination to return). Processing steps: validate the item number, look up the price, check the stock count, repeatedly input and accumulate coins while the total < price, reject invalid coins, compute total change = amount inserted - price, apply a greedy algorithm to determine the fewest coins for change, decrement the stock count for the chosen item.

输入:商品编号(整数 1-3),逐枚投入的硬币面额(代表有效面额的实数)。输出:确认信息(‘商品已发放’ 或 ‘缺货’ 或 ‘金额不足’),找零明细(每种面额硬币各需退回几枚)。处理步骤:验证商品编号,查找价格,检查库存数量,在 total < price 的情况下反复输入并累加硬币,拒绝无效面额,计算总找零 = 已投金额 – 价格,运用贪心算法确定最少硬币找零方案,将所选商品的库存计数减 1。


4. Data Structures and Variables | 数据结构与变量

We will use three parallel arrays (lists) to store item information: itemNames = ['Crisps','Chocolate','Water'], prices = [1.20, 0.90, 0.70] and stock = [10, 10, 10] (initial stock of 10 each). The valid coin denominations are stored in an array coins = [1.00, 0.50, 0.20, 0.10, 0.05]. Key variables include: choice (integer), price (real), totalInserted (real, initially 0), coinInput (real), change (real) and an array changeCoins of length 5 to hold the number of each coin to return.

我们将使用三个平行数组(列表)储存商品信息:itemNames = ['Crisps','Chocolate','Water']prices = [1.20, 0.90, 0.70] 以及 stock = [10, 10, 10](初始库存各 10 个)。有效硬币面额储存在数组 coins = [1.00, 0.50, 0.20, 0.10, 0.05] 中。重要变量包括:choice(整数)、price(实数)、totalInserted(实数,初值 0)、coinInput(实数)、change(实数)以及长度为 5 的数组 changeCoins 用于存放每种硬币的退回数量。


5. Algorithm Design – Pseudocode | 算法设计 – 伪代码

The core logic can be expressed as follows. Pay attention to the loop structure and the use of DIV and MOD to decompose change into individual coin counts.

核心逻辑可用以下方式表达。留意循环结构以及如何用 DIV 和 MOD 将找零分解为各面额的硬币数量。

Main Program Pseudocode

OUTPUT menu with item names, prices and numbers
INPUT choice
IF choice < 1 OR choice > 3 THEN
    OUTPUT "Invalid selection"
    STOP
ENDIF
IF stock[choice-1] = 0 THEN
    OUTPUT "Out of stock"
    STOP
ENDIF
price ← prices[choice-1]
totalInserted ← 0
WHILE totalInserted < price DO
    INPUT coinInput
    IF coinInput is in coins[] THEN
        totalInserted ← totalInserted + coinInput
    ELSE
        OUTPUT "Invalid coin, please insert a valid coin"
    ENDIF
ENDWHILE
change ← totalInserted - price
FOR i ← 0 TO 4
    changeCoins[i] ← change DIV coins[i]   // integer division
    change ← change MOD coins[i]            // remainder in pence converted appropriately
ENDFOR
stock[choice-1] ← stock[choice-1] - 1
OUTPUT "Item dispensed. Change: "
FOR i ← 0 TO 4
    IF changeCoins[i] > 0 THEN
        OUTPUT changeCoins[i], " x £", coins[i]
    ENDIF
ENDFOR

上述伪代码首先输出菜单并读取用户选择;验证编号并在缺货时终止;获取价格后进入硬币投入循环,仅当投入面额有效时才累加;总额足够后计算找零总额,并通过一个循环用贪心策略从大到小分配硬币;最后更新库存并输出找零明细。注意伪代码中硬币数组以英镑为单位,求余部分已经隐含面额换算,实际实现时需要小心处理浮点数精度,一般将金额转换为整数(以便士为单位)进行计算。


6. Designing Test Data | 设计测试数据

Testing must cover normal, boundary and erroneous cases. The table below shows a representative test plan. We assume initial stock of 10 for each item.

测试必须覆盖正常、边界和错误情况。下表展示了代表性测试计划,并假设每种商品初始库存为 10。

Test Case (English) 测试用例 Inputs Expected Outcome
Normal purchase with exact amount 正常购买,恰好金额 Choice=2, insert 50p, 20p, 20p Item dispensed, change = 0, stock[1] becomes 9
Normal purchase with change required 正常购买,需要找零 Choice=1, insert £1, 20p, 10p Item dispensed, change = 10p (1×10p), stock[0] becomes 9
Boundary: insert first coin that makes total equal 边界:首币恰好满足 Choice=3, insert £1 Item dispensed, change = 30p (1×20p+1×10p), stock[2] becomes 9
Boundary: stock = 1, buy last item 边界:库存为 1,购买最后一件 Set stock[2]=1, choice=3, insert £1, 5p Item dispensed, change = 35p, stock becomes 0
Error: invalid item number 错误:无效商品编号 Choice=5 “Invalid selection”, program stops
Error: out of stock 错误:库存不足 Set stock[0]=0, choice=1 “Out of stock”, program stops
Error: invalid coin inserted then valid coin 错误:插入无效硬币后继续 Choice=2, insert 2p, then insert 50p, 40p? 2p rejected (“Invalid coin”), 50p accepted, eventually total ≥ 0.90, dispensed

Note that all monetary amounts should be handled in integer pence (e.g. 120, 90, 70) to avoid floating-point rounding errors. The test data above uses pounds for readability, but the implementation multiplies by 100.

请注意,为防止浮点数舍入误差,所有金额应在程序内部以整数便士(如 120、90、70)进行处理。上表为可读性使用英镑单位,但实现时会将数值乘以 100。


7. Validation and Verification | 验证与检验

Validation checks ensure only sensible data enters the system. At the item selection stage, we perform a range check: the input must be an integer between 1 and 3. At the coin insertion stage, we check that the entered value exactly matches one of the allowed denominations – this can be implemented by comparing coinInput (converted to pence) to a list of valid pence values. Additionally, a presence check prevents empty input. Verification involves re-running the test plan and checking that the actual outputs match the expected ones. A manual trace through the pseudocode with a sample input can be used for desk checking.

验证环节确保只有合理数据进入系统。在商品选择阶段,我们进行范围检查:输入必须是 1 到 3 之间的整数。在硬币投入阶段,检查输入值是否与允许的面额之一精确匹配——实现时可将 coinInput 转为便士整数并与有效值列表比较。此外,存在性检查可防止空输入。检验则涉及重新执行测试计划并确认实际输出与预期一致。也可以通过纸笔追踪伪代码在某组输入下的执行过程进行桌面检查。


8. Implementation in Python (Outline) | Python 实现提纲

When translating the algorithm into Python, we can use lists for the parallel arrays and a while loop for coin insertion. The change calculation can use a combination of integer division // and modulo % after converting the change to an integer in pence. A for loop will iterate over the coins list. The snippet below captures the stock update and change distribution, but you should also include input validation as described earlier.

将算法翻译为 Python 时,可以用列表表示平行数组,用 while 循环控制硬币投入。找零计算可先将找零金额转为便士整数,然后结合整除 // 与取余 %。一个 for 循环会遍历硬币列表。以下代码段展示了库存更新和找零分配,但你还应根据前面描述加入输入验证。

# assume choice validated, price_f retrieved
change_pence = int((total_inserted - price_f) * 100 + 0.5)  # rounding safeguard
coin_values_pence = [100, 50, 20, 10, 5]
change_breakdown = []
for coin in coin_values_pence:
    count = change_pence // coin
    change_breakdown.append(count)
    change_pence %= coin
# update stock
stock[choice-1] -= 1

Remember to multiply all prices and coin inputs by 100 at the earliest point and work exclusively with integers to avoid the inaccuracies of floating-point arithmetic. Also, you need to accumulate total_inserted in pence.

请记住尽早将所有价格和硬币输入乘以 100 并全程使用整数运算,以避免浮点数的不精确性。同时,total_inserted 也应以便士为单位进行累加。


9. Extending with File Handling | 使用文件处理扩展

In a more realistic system, stock levels should persist between program runs. This can be achieved by reading the initial stock from a text file at startup and writing the updated stock back to the file when the program ends. For example, a file stock.txt could contain three lines: 10, 10, 10. The program would open the file in read mode, load the values into the stock array, and later overwrite the file with the new stock counts. This addition gives you practice with file I/O, which is a frequent topic in IGCSE practical problem-solving tasks.

在更贴近实际的系统中,库存水平应在多次程序运行间保持。这可以通过在启动时从文本文件读取初始库存、程序结束时将更新后的库存写回文件来实现。例如,文件 stock.txt 可包含三行:10、10、10。程序以读模式打开文件,将值载入 stock 数组,随后用新的库存计数覆写文件。这一扩展让你有机会练习文件输入/输出,而这是 IGCSE 实践问题解决题中常见的内容。


10. Evaluation and Improvements | 评估与改进

The current solution is effective for a small-scale vending machine, but it has limitations. It does not handle the case where the machine cannot provide exact change (change shortage). A real vending machine would reject the transaction if the coin reservoir is insufficient. The system also assumes that coins are inserted one at a time – it could be extended to accept a single bulk payment using a coin acceptor simulation. Further, there is no user authentication or transaction logging. For enhanced robustness, we could store data in a database and include a graphical user interface. From an algorithmic perspective, the greedy change algorithm works only because the UK coin denominations are canonical; for arbitrary denominations a dynamic programming approach would be needed.

当前解决方案对于小型自动售货机是有效的,但存在局限。它没有处理机器无法提供准确找零(零钱不足)的情形。真实的售货机会在硬币储备不够时拒绝交易。系统也假定硬币是逐枚投入的——可以扩展为通过硬币接收器模拟一次性投入全部支付。此外,没有用户认证或交易记录功能。为了增强健壮性,可以将数据储存在数据库中并加入图形用户界面。从算法角度看,贪心找零算法只适用于英国硬币面额体系(其具有规范性);面对任意面额时则需要动态规划方法。

Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading