📚 Identifying Errors in Algorithms | 识别算法中的错误
Algorithms are step-by-step instructions for solving a problem. Even a small mistake in one step can produce incorrect results. In the IGCSE CIE Computer Science syllabus, you must be able to identify errors in algorithms, use trace tables, and suggest corrections. This skill is essential for both paper-based exams and practical programming tasks.
算法是解决问题的分步指令。即使一步出错,也可能导致结果错误。在 IGCSE CIE 计算机科学课程中,你必须能够识别算法中的错误、使用追踪表并提出修正方法。这项技能对于笔试和实际编程任务都至关重要。
1. What Are Algorithm Errors? | 什么是算法错误?
An algorithm error is any mistake in the logic, syntax, or structure of an algorithm that causes it to behave incorrectly. Errors can occur at the design stage, during coding, or when the algorithm is used with unexpected data.
算法错误是指算法在逻辑、语法或结构上的任何错误,导致其行为异常。错误可能出现在设计阶段、编码过程中,或者当算法遇到意外数据时。
For IGCSE, you are expected to distinguish between two main categories of errors: syntax errors and logic errors. Recognising the type of error is the first step toward fixing it.
在 IGCSE 考试中,你需要区分两大类错误:语法错误和逻辑错误。识别错误类型是修复错误的第一步。
2. Syntax Errors vs Logic Errors | 语法错误与逻辑错误
A syntax error occurs when the rules of a programming language are violated. For example, writing ‘PRINTT’ instead of ‘PRINT’ or missing a closing bracket. The computer cannot understand the instruction, so the program stops immediately. Syntax errors are easy to find because the compiler or interpreter reports them.
语法错误是指违反编程语言规则,例如把 PRINT 写成 PRINTT,或漏掉右括号。计算机无法理解该指令,程序会立即停止。语法错误比较容易发现,因为编译器或解释器会报告它们。
A logic error occurs when the algorithm runs without stopping, but produces the wrong answer. For example, using ‘=’ instead of ‘
逻辑错误是指算法可以运行而不中断,但产生错误结果。例如,在比较时用了 ‘=’ 而不是 ‘
| Feature | 特征 | Syntax Error | 语法错误 | Logic Error | 逻辑错误 |
|---|---|---|
| Program stops? | 程序是否停止? | Yes | 是 | No, it keeps running | 否,继续运行 |
| Detected by | 检测方式 | Compiler / interpreter | 编译器 / 解释器 | Testing and trace tables | 测试和追踪表 |
| Output | 输出 | No output | 无输出 | Wrong output | 错误输出 |
3. Trace Tables | 追踪表
A trace table is a structured way to record the value of every variable and the outcome of every condition as the algorithm is executed step by step. Trace tables are a powerful tool for detecting logic errors because they show exactly how data changes through the algorithm.
追踪表是一种结构化的方法,逐步记录算法执行过程中每个变量的值和每个条件的结果。追踪表是发现逻辑错误的有力工具,因为它能精确显示数据在算法中的变化过程。
To build a trace table, draw a column for each variable and a column for any output. Follow the algorithm line by line and update the table each time a variable changes. If the final values do not match the expected result, you have found the error.
要建立追踪表,为每个变量画一列,并设置一列用于输出。逐行执行算法,每当变量变化时更新表格。如果最终值与预期结果不符,就说明找到了错误。
Example algorithm: calculate the sum of numbers from 1 to 4.
示例算法:计算 1 到 4 的和。
total ← 0
FOR i ← 1 TO 4
total ← total + i
ENDFOR
OUTPUT total
| i | i 的值 | total | total 的值 | Output | 输出 |
|---|---|---|
| 1 | 1 | – |
| 2 | 3 | – |
| 3 | 6 | – |
| 4 | 10 | 10 |
4. Dry Running an Algorithm | 手工执行算法
Dry running means executing an algorithm by hand, without using a computer. You use a pen and paper to follow each instruction and record all variable changes. This is the simplest way to spot errors, especially in loops and conditional statements.
手工执行(Dry Run)是指不用计算机,而是用纸笔逐步执行算法。你逐个指令跟踪并记录所有变量变化。这是发现错误最简单的方法,尤其是循环和条件语句中的错误。
When dry running, always write down your assumptions about the input. For example, if an algorithm expects a positive number, test with normal values like 5, and also test with extreme values like 0 or a negative number. This helps you see whether the algorithm handles all possible cases correctly.
手工执行时,一定要写明对输入的假设。例如,如果算法期望正数,用 5 这样的正常值测试,同时也要用 0 或负数等极端值测试。这有助于你判断算法是否能正确处理所有可能情况。
5. Common Logic Errors | 常见逻辑错误
Certain logic errors appear frequently in IGCSE questions. You should be able to recognise these patterns immediately.
某些逻辑错误在 IGCSE 题目中经常出现。你应该能立刻识别这些模式。
- Off-by-one error | 差一错误:A loop runs one time too many or one time too few. For example, using ‘i <= 5’ instead of ‘i < 5’ when only 4 iterations are intended. | 循环多执行一次或少执行一次。例如,本应循环 4 次却写成 ‘i <= 5’。
- Incorrect initialisation | 初始化错误:Variables that are used for summing or counting must start at 0. If total is initialised to 1, every sum will be 1 too high. | 用于求和或计数的变量必须从 0 开始。如果 total 初始化为 1,所有求和结果都会多 1。
- Wrong comparison operator | 比较运算符错误:Using ‘>’ when ‘>=’ is needed, or using ‘=’ instead of ‘==’ in some languages, changes the boundary of a decision. | 该用 ‘>=’ 却用了 ‘>’,会改变判断的边界条件。
- Incorrect order of conditions | 条件顺序错误:In a multi-branch IF statement, the first matching condition is executed. If a general condition comes before a specific one, some branches become unreachable. | 在多分支 IF 语句中,第一个满足的条件会被执行。如果一般条件放在特殊条件之前,某些分支将永远不会执行。
- Missing or extra variable update | 变量更新缺失或多余:Forgetting to add 1 to a loop counter causes an infinite loop. Updating a variable in the wrong place can also corrupt results. | 忘记给循环计数器加 1 会导致死循环。在错误的位置更新变量也会破坏结果。
6. Test Data: Normal, Boundary, Invalid | 测试数据:正常、边界、无效
To identify errors in an algorithm, you must choose test data carefully. Normal data tests typical inputs, boundary data tests the edges of allowed ranges, and invalid data tests how the algorithm handles unexpected inputs.
要识别算法错误,必须精心选择测试数据。正常数据测试典型输入,边界数据测试允许范围的边缘,无效数据则测试算法如何处理意外输入。
| Type | 类型 | Definition | 定义 | Example (marks 0-100) | 示例(成绩 0-100) |
|---|---|---|
| Normal | 正常 | Valid, typical input | 有效、典型输入 | 50, 75 |
| Boundary | 边界 | Values at the limits of the range | 范围极限处的值 | 0, 100, also 1 and 99 if rounding is used |
| Invalid | 无效 | Values outside the valid range | 有效范围之外的值 | -5, 150, “A” |
If an algorithm works with normal data but fails with boundary data, the error is usually a loop boundary or a comparison operator issue. If it fails with invalid data, the algorithm probably lacks a validation step.
如果算法对正常数据有效,但在边界数据时出错,错误通常是循环边界或比较运算符问题。如果算法在无效数据时出错,则很可能缺少数据验证步骤。
7. Debugging Techniques | 调试技术
Once you have identified a possible error, you need to debug the algorithm. Debugging is the process of finding and correcting errors. Several techniques can help.
一旦发现可能的错误,你需要调试算法。调试就是查找并纠正错误的过程。有几种技巧可以帮助你。
- Add temporary output statements | 添加临时输出语句:Insert a print statement inside a loop to show the value of a variable at each iteration. This can reveal where the value becomes unexpected. | 在循环内插入输出语句,显示每次迭代时变量的值。这能揭示数值在何处变得异常。
- Use a trace table | 使用追踪表:This is the most reliable method for exams. Write down each step and compare with the expected behaviour. | 这是考试中最可靠的方法。写下每一步并与预期行为比较。
- Check boundary conditions | 检查边界条件:Ask: what happens at the first and last iteration of a loop? What happens when the input is the smallest or largest allowed value? | 问问自己:循环第一次和最后一次迭代会发生什么?输入是最小或最大允许值时会发生什么?
- Work backwards from the answer | 从答案逆推:If the expected output is known, start from the output and trace back through the algorithm to see where the calculation goes wrong. | 如果已知预期输出,从输出开始沿算法逆推,看计算在哪一步出错。
8. Worked Example 1: Average Calculation | 实例 1:计算平均值
Consider this algorithm that is supposed to read numbers until the user enters -1, then output the average.
考虑以下算法:它应读取数字直到用户输入 -1,然后输出平均值。
sum ← 0
count ← 0
INPUT num
WHILE num ≠ -1
sum ← sum + num
count ← count + 1
INPUT num
ENDWHILE
OUTPUT sum / count
Identify the error. If the user enters -1 immediately, count is 0, and the algorithm divides by zero. This is a logic error: there is no check for count > 0 before calculating the average. The corrected version should include an IF statement.
请找出错误。如果用户立即输入 -1,count 为 0,算法会除以零。这是一个逻辑错误:在计算平均值前没有检查 count > 0。修正版本应包含 IF 语句。
IF count > 0 THEN
OUTPUT sum / count
ELSE
OUTPUT “no data”
ENDIF
This example shows that even a simple logical omission can cause a runtime problem. Trace tables help you notice that count remains 0 when the first input is the sentinel value.
这个例子表明,即使一个简单的逻辑遗漏也可能导致运行时问题。追踪表能帮助你注意到,当第一个输入就是终止值时,count 仍为 0。
9. Worked Example 2: Sum of First Five Numbers | 实例 2:前五个数的和
This algorithm is intended to output the sum of the integers from 1 to 5 inclusive.
以下算法旨在输出从 1 到 5(含)的整数之和。
total ← 0
FOR i ← 0 TO 5
total ← total + i
ENDFOR
OUTPUT total
Using a trace table, we see that i takes the values 0, 1, 2, 3, 4, 5, so total becomes 15. However, the intended range is 1 to 5, which also sums to 15 in this case. But if the intention was to sum 1 to 4, this algorithm would be wrong. The key point is that the loop should start at i = 1 if 0 should not be included.
使用追踪表可以看到,i 取 0, 1, 2, 3, 4, 5,所以 total 为 15。但本例中本意是 1 到 5,和也为 15。然而,如果本意是求 1 到 4 的和,该算法就错了。关键点是:如果不需要包含 0,循环应从 i = 1 开始。
| i | total |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
| 4 | 10 |
| 5 | 15 |
This illustrates an off-by-one error. Always check the start and end values of a FOR loop when trying to identify errors.
这体现了差一错误。在识别错误时,务必检查 FOR 循环的起始值和结束值。
10. Worked Example 3: Grade Decision | 实例 3:成绩判定
The rule is: marks ≥ 80 give grade A; marks ≥ 60 give grade B; marks ≥ 40 give grade C; otherwise grade D. Consider this algorithm.
规则是:成绩 ≥ 80 得 A;≥ 60 得 B;≥ 40 得 C;其余得 D。请看以下算法。
IF marks ≥ 40 THEN
grade ← “C”
ELSE IF marks ≥ 60 THEN
grade ← “B”
ELSE IF marks ≥ 80 THEN
grade ← “A”
ELSE
grade ← “D”
ENDIF
The first condition catches every mark over 40, so no student can ever receive a grade A or B. The conditions are in the wrong order. They must be tested from highest to lowest requirement.
第一个条件会捕获所有 40 分以上的成绩,因此不会有学生得到 A 或 B。条件顺序错了。必须按从最高到最低的要求依次测试。
IF marks ≥ 80 THEN
grade ← “A”
ELSE IF marks ≥ 60 THEN
grade ← “B”
ELSE IF marks ≥ 40 THEN
grade ← “C”
ELSE
grade ← “D”
ENDIF
When identifying errors, always examine the order of IF-ELSE IF conditions and test each boundary value. A trace table with marks = 85 would show that the first incorrect version outputs “C” instead of “A”.
识别错误时,始终检查 IF-ELSE IF 条件的顺序,并对每个边界值进行测试。使用 marks = 85 的追踪表会显示,错误版本输出 “C” 而不是 “A”。
11. Error Identification Checklist | 错误识别检查清单
Use this checklist when examining an algorithm for errors in an exam question.
在考试中检查算法错误时,请使用这份检查清单。
- Are all variables initialised correctly? | 所有变量是否正确初始化?
- Are loop start and end values correct? | 循环的起始值和结束值是否正确?
- Are the comparison operators correct (>, <, ≥, ≤)? | 比较运算符是否使用正确(>, <, ≥, ≤)?
- Are the conditions in IF statements in the correct order? | IF 语句中的条件顺序是否正确?
- Is there any division that could be by zero? | 是否存在除以零的可能性?
- Are counters and accumulators updated inside the correct part of the loop? | 计数器和累加器是否在循环的正确位置更新?
- Does the loop terminate for every possible input? | 对每个可能的输入,循环都能终止吗?
- Is the output statement placed after the calculation, not inside a repetition unnecessarily? | 输出语句是否放在计算之后,而不是不必要地放在循环内部?
- Are all possible branches of an IF statement covered? | IF 语句的所有可能分支是否都被覆盖?
- Have boundary and invalid test values been considered? | 是否考虑了边界值和无效测试值?
12. Summary | 总结
Identifying errors in algorithms is a core skill in IGCSE CIE Computer Science. Syntax errors are easy to detect because the system reports them, but logic errors require careful testing and tracing. You can find logic errors by using trace tables, dry running the algorithm, choosing boundary and invalid test data, and checking common error patterns such as off-by-one mistakes and incorrect condition order.
识别算法错误是 IGCSE CIE 计算机科学的核心技能。语法错误很容易发现,因为系统会报告它们;但逻辑错误需要仔细测试和追踪。你可以通过使用追踪表、手工执行算法、选择边界值和无效测试数据,以及检查常见错误模式(如差一错误和条件顺序错误)来发现逻辑错误。
Always practise with past paper questions. Draw a trace table for every algorithm you meet, and test every branch with normal, boundary, and invalid data. With systematic practice, you will quickly identify the hidden errors that examiners love to include.
始终用真题进行练习。为每一个遇到的算法绘制追踪表,并用正常数据、边界数据和无效数据测试每个分支。通过系统练习,你将能迅速发现考官喜欢隐藏的错误。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply