跳到主要内容

算法设计与问题求解

A-Level 计算机科学知识点 9

本主题的视频课程 打开视频页面
14:30

计算思维

这里有一个任务:构建一个系统来管理整家商店的库存——每种产品、每笔销售、每次送货、每份报告。作为一个整体问题,它太大以至于……

英文讲解 · 可切换中英文字幕

9.1

计算思维技能

教学大纲
考生应能够: 注释与指导
展示对**抽象(abstraction)**的理解 使用抽象的必要性与优势;描述抽象的目的;仅包含关键细节,从而为系统生成一个抽象模型
描述并运用分解(decomposition) 将问题拆解为子问题,进而引出程序模块(过程/procedure / 函数/function)的概念

来源:Cambridge International 教学大纲

English

Computational thinking 计算思维 is the set of mental tools for analysing a problem and designing a solution a computer can run. Two key ones are abstraction and decomposition.

A part-finished jigsaw puzzle
Computational thinking breaks a big problem into smaller, easier parts — like solving a jigsaw

Abstraction

Abstraction 抽象 means keeping the essential features of a problem and ignoring the irrelevant detail, giving a simpler model.

Examples:

  • a train-network map keeps the stations and lines but drops the geography.
  • a class in object-oriented programming keeps only the attributes and methods the system needs.
  • a function hides a piece of work behind a name.

A full model of any real problem would be too big to reason about, so abstraction is essential.

The examiner asks for the purpose of abstraction and for its benefits. Purpose: to produce a simpler model of a problem that contains only the details needed to solve it. Benefits: the problem is easier to understand and to program; the program is smaller and faster to write and test; the same model can be reused for similar problems. When you are asked to produce an abstract model of a system, list only the data and actions the task needs. For a school timetable that means the classes, rooms, teachers and periods; it does not mean the colour of the rooms or the age of the teachers.

Abstraction turns a cluttered real geography (a wiggly route with scattered buildings) into a clean metro map — evenly spaced station circles on a straight line, keeping the stations and lines and dropping the geography
Abstraction keeps the essentials (stations and lines) and drops irrelevant detail (the geography)

Decomposition

Decomposition 分解 means breaking a large problem into smaller sub-problems, each easier to solve and tackled one at a time.

  1. find the main parts of the task.
  2. break each into smaller sub-tasks.
  3. continue until each is small enough to design directly.
  4. solve the small tasks and combine them.

For stock control: "manage stock" → "record sales", "record deliveries", "produce reports" → ("record sales") "look up product", "decrease stock count", "save the transaction". Decomposition makes big problems manageable, lets a team divide the work, and gives modular code — each module becomes a procedure 过程 or function.

"Explain why decomposition is used" is a three-mark question with a fixed shape. Give three separate benefits: each sub-problem 子问题 is small enough to design, code and test on its own; different programmers can work on different modules 模块 at the same time; a module that already exists (or a library routine) can be reused, and a fault is easier to find because it lies inside one module. A structure chart (topic 12) is the diagram of a decomposition: the program at the top, its modules beneath, and the data passed between them.

A tree with "Manage stock" at the top branching into the modules "Record sales", "Record deliveries" and "Produce reports", and "Record sales" splitting into the sub-tasks "Look up product", "Decrease stock count" and "Save the transaction"
Decomposing a program into modules and sub-modules
探索

用计算的方式解决一个问题

按你会使用它们的顺序逐步走过四个基石——把问题拆开,发现什么重复,剥到本质,然后写步骤。

词汇 训练
English 中文 拼音
computational thinking/ˌkɒmpjuːˈteɪʃənl ˈθɪŋkɪŋ/ 计算思维 jì suàn sī wéi
abstraction/əbˈstrækʃn/ 抽象 chōu xiàng
decomposition/ˌdiːkɒmpəˈzɪʃn/ 分解 fēn jiě
sub-problem/sʌb ˈprɒbləm/ 子问题 zi wèn tí
procedure/prəˈsiːdʒə/ 过程 guò chéng
modules/ˈmɒdjuːlz/ 模块 mó kuài
9.2

算法

教学大纲
考生应能够: 注释与指导
展示对算法的理解,即算法是问题解决方案的表述,由一系列定义明确的步骤组成
为问题所使用数据的表示选用合适的标识符名称,并使用标识符表来表示这些名称
编写包含输入、处理和输出的伪代码
使用顺序、选择和迭代(重复)三种基本结构编写伪代码
使用结构化英文描述、流程图或伪代码来记录一个简单的算法
根据以下内容编写伪代码:• 结构化英文描述 • 流程图
根据以下内容绘制流程图:• 结构化英文描述 • 伪代码
描述并运用逐步细化过程来表达一个算法,直至达到可以从该细节水平进行编程的程度
使用逻辑语句来定义算法解决方案的部分

来源:Cambridge International 教学大纲

English
Bubble sort, pass by pass

An algorithm 算法 is a solution expressed as a sequence of defined steps. Each step is unambiguous 无歧义 (one meaning), deterministic 确定性 (same input → same output), finite (the steps end), and effective (each can be done). An algorithm says what to do, independent of the programming language used to implement it.

探索

选择:跟随 IF / ELSE 分支

拖动分数,看哪个分支运行。选择依次测试每个条件,取第一个为真的——这就是 IF … ELSE IF … ELSE 的工作方式。

词汇 训练
English 中文 拼音
algorithm/ˈælɡərɪθəm/ 算法 suàn fǎ
unambiguous/ʌnæmˈbɪɡjuːəs/ 无歧义 wú qí yì
deterministic/dɪˌtɜːmɪˈnɪstɪk/ 确定性 què dìng xìng
9.2

标识符表

English

When you start an algorithm, list every piece of data in an identifier table 标识符表 — its identifier 标识符 (the variable 变量 name), data type 数据类型, and description. The exam's table has exactly these three columns:

Identifier Data type Description
Category STRING the product category
SaleDate DATE when the item was sold
ItemCost REAL cost of the item
InStock BOOLEAN TRUE if in stock
Sales ARRAY[1:30] OF REAL the last 30 daily sales totals

Use descriptive names (ItemCost, not x): an identifier starts with a letter, contains no spaces, and is written the same way every time it appears. Common types are INTEGER, REAL, STRING, CHAR, BOOLEAN, DATE, plus arrays. The table forces you to name every piece of data before writing code, and a "complete the identifier table" question gives one mark for each correct data type or description, so write the type exactly as the pseudocode guide does.

An identifier table listing each variable with its name, data type and description, for example ItemCost as a REAL for the cost of the item
An identifier table names every piece of data before you write code
词汇 训练
English 中文 拼音
identifier table/aɪˈdentɪfaɪə ˈteɪbl/ 标识符表 biāo shí fú biǎo
identifier/aɪˈdentɪfaɪə/ 标识符 biāo shí fú
variable/ˈveərɪəbl/ 变量 biàn liàng
data type/ˈdeɪtə taɪp/ 数据类型 shù jù lèi xíng
9.2

伪代码 —— 三种基本结构

English

Pseudocode 伪代码 is a structured, language-neutral way to describe algorithms.

The three basic constructs as mini-flowcharts: sequence runs step A then B then C; selection tests a condition and does X or Y; iteration repeats a body while a condition holds, looping back
The three building blocks of any algorithm: sequence, selection and iteration

1. Sequence

Steps run one after another (sequence 顺序):

INPUT Name
INPUT Age
OUTPUT "Hello", Name

2. Selection

A choice of which steps run, based on a condition (selection 选择):

IF Age >= 18 THEN
    OUTPUT "Adult"
ELSE
    OUTPUT "Minor"
ENDIF

For more options, use CASE OF ... ENDCASE.

3. Iteration

Repeating a block (iteration 迭代, a loop 循环):

FOR i ← 1 TO 10
    OUTPUT i
NEXT i

A WHILE loop tests the condition before each pass (may run zero times); a REPEAT...UNTIL loop tests after each pass (always runs at least once).

WHILE Total < 100 DO
    INPUT Value
    Total ← Total + Value
ENDWHILE

REPEAT
    INPUT Mark
UNTIL Mark >= 0 AND Mark <= 100
Two flowcharts side by side. WHILE tests the condition first, so the body may never run: the diamond sits above the body and the No branch leaves the loop. REPEAT UNTIL runs the body first and tests after it, so the body always runs at least once: the body sits above the diamond and the No branch returns to it
A WHILE loop tests before the body runs; a REPEAT ... UNTIL loop tests after it, so its body always runs at least once

Choosing the loop is itself a mark: FOR when you know how many times (a count-controlled loop 计数循环); WHILE when the loop might not run at all (a pre-condition loop 前测循环); REPEAT ... UNTIL when it must run at least once, as in validating an input (a post-condition loop 后测循环). A "describe the iteration construct" answer names the construct, says where the condition is tested, and gives the consequence (zero times or at least once).

Common operations

  • assignment 赋值: x ← 5 (an arrow; = is for comparison).
  • input/output: INPUT variable, OUTPUT expression.
  • comparisons =, <>, <, >, <=, >=; logic AND, OR, NOT.
  • arithmetic + - * /, plus DIV (integer division) and MOD (remainder).
  • strings: LENGTH, LEFT, RIGHT, MID, and & for concatenation 拼接 (joining).

The pseudocode the exam expects

Every pseudocode answer is marked against Cambridge's published pseudocode guide. Write these forms exactly:

Construct Pseudocode
Variable DECLARE Total : INTEGER
Array DECLARE Marks : ARRAY[1:30] OF REAL
Constant CONSTANT MaxTries = 3
Assignment Total ← Total + Value
Input / output INPUT Name
OUTPUT "Hello ", Name
Selection CASE OF Choice
1 : OUTPUT "Add"
OTHERWISE OUTPUT "Error"
ENDCASE
FOR loop FOR i ← 1 TO 10 STEP 2 ... NEXT i
WHILE loop WHILE Total < 100 DO ... ENDWHILE
REPEAT loop REPEAT ... UNTIL Mark >= 0
Integer arithmetic 17 DIV 5 = 3
17 MOD 5 = 2
Strings LENGTH(S), LEFT(S, 3), RIGHT(S, 2)
MID(S, 2, 4), TO_UPPER(S), TO_LOWER(S)
Conversions INT(3.7) = 3, NUM_TO_STR(12)
STR_TO_NUM("4.5"), ASC('A') = 65, CHR(66) = 'B'
Random RAND(100)
INT(RAND(100)) + 1

RAND(100) gives a real number from 0 up to (but not including) 100. INT(RAND(100)) + 1 gives an integer from 1 to 100.

Two habits earn marks on every question: declare every variable you use, with the type from your identifier table, and initialise 初始化 every counter 计数器 and total (Count ← 0, Total ← 0) before the loop that changes it.

Input → Process → Output

Every program follows this shape:

INPUT Length
INPUT Width
Area ← Length * Width
OUTPUT "Area = ", Area

Listing the inputs and outputs first makes the algorithm cleaner.

Worked example. Write pseudocode that inputs 100 integers and outputs how many of them, and the total of those, that lie between 10 and 20 inclusive.

Identifier table: Count : INTEGER (loop counter), Value : INTEGER (the integer just input), InRange : INTEGER (how many were in range), Total : INTEGER (their sum).

DECLARE Count, Value, InRange, Total : INTEGER
InRange ← 0
Total ← 0
FOR Count ← 1 TO 100
    INPUT Value
    IF Value >= 10 AND Value <= 20 THEN
        InRange ← InRange + 1
        Total ← Total + Value
    ENDIF
NEXT Count
OUTPUT InRange, Total

If the question then asks you to "identify two constructs and state how each is used", answer in the same shape: iteration, the FOR loop, repeats the input 100 times; selection, the IF statement, adds a value only when it is in range.

Worked example. A program picks a secret integer from 1 to 100. The user guesses until they are right; after each wrong guess the program says "Too low" or "Too high", and at the end it outputs how many guesses were made.

Identifier table: Secret : INTEGER (the number to guess), Guess : INTEGER (the user's input), Tries : INTEGER (how many guesses so far).

DECLARE Secret, Guess, Tries : INTEGER
Secret ← INT(RAND(100)) + 1
Tries ← 0
REPEAT
    INPUT Guess
    Tries ← Tries + 1
    IF Guess < Secret THEN
        OUTPUT "Too low"
    ELSE
        IF Guess > Secret THEN
            OUTPUT "Too high"
        ENDIF
    ENDIF
UNTIL Guess = Secret
OUTPUT "You took ", Tries, " guesses"

A REPEAT ... UNTIL loop is the right choice because the user must guess at least once. The marks are for: the random number in the right range, a loop that ends on a correct guess, the counter that starts at zero and increases inside the loop, the two messages under the right conditions, and the final output.

Flowchart of the guessing game: Start, then set Secret to a random integer from 1 to 100 and Tries to 0, then input a guess, add one to Tries, test whether the guess equals the secret (Yes leads to output Tries and Stop), otherwise test whether the guess is smaller (Yes outputs Too low, No outputs Too high), and both outputs loop back to the input
The same guessing game as a flowchart: the two decision diamonds are the two IF statements, and the return arrow is the REPEAT ... UNTIL loop

Worked example. Output two different random integers, each between $-10$ and $10$ inclusive.

There are 21 possible values, so INT(RAND(21)) gives 0 to 20 and subtracting 10 shifts it to the range $-10$ to $10$. The second number must be generated again until it differs from the first:

DECLARE First, Second : INTEGER
First ← INT(RAND(21)) - 10
REPEAT
    Second ← INT(RAND(21)) - 10
UNTIL Second <> First
OUTPUT First, Second
Every program follows the shape input, then process, then output, shown with the area example: input the length and width, process by multiplying, output the area
Every program follows the Input, Process, Output shape
探索

IF … ELSE 选择结构

改变数值,观察哪个分支运行——程序如何做出决策。

词汇 训练
English 中文 拼音
sequence/ˈsiːkwəns/ 顺序 shùn xù
pseudocode/ˈsuːdəʊkəʊd/ 伪代码 wěi dài mǎ
selection/sɪˈlekʃn/ 选择 xuǎn zé
iteration/ˌɪtəˈreɪʃn/ 迭代 dié dài
loop/luːp/ 循环 xún huán
count-controlled loop/kaʊnt kənˈtrəʊld luːp/ 计数循环 jì shù xún huán
pre-condition loop/priː kənˈdɪʃn luːp/ 前测循环 qián cè xún huán
post-condition loop/pəʊst kənˈdɪʃn luːp/ 后测循环 hòu cè xún huán
assignment/əˈsaɪnmənt/ 赋值 fù zhí
concatenation/kənˌkætəˈneɪʃn/ 拼接 pīn jiē
initialise/ɪˈnɪʃəlaɪz/ 初始化 chū shǐ huà
counter/ˈkaʊntə/ 计数器 jì shù qì
9.2

三种表示法

English

The same algorithm can be written three ways.

  • structured English 结构化英语 — natural language with indentation and fixed keywords; good for a high-level description.
  • flowchart 流程图 — a diagram with standard shapes:
Shape Meaning
Rounded rectangle Start / Stop
Parallelogram Input / Output
Rectangle Process
Diamond Decision
Arrow Flow of control
  • pseudocode — the keyword notation above; closest to code.

You should be able to convert between any pair: each IF is a decision diamond, each loop is a back-arrow, and a sequence is stacked rectangles.

IF ... THEN ... ELSE ... ENDIF

A flowchart for averaging numbers: rounded Start and Stop terminators, input/output parallelograms, process rectangles, and a "count < n?" decision diamond whose Yes branch loops back to read the next value
A flowchart for averaging a list of numbers, using the standard shapes
词汇 训练
English 中文 拼音
flowchart/ˈfləʊtʃɑːt/ 流程图 liú chéng tú
structured English/ˈstrʌktʃəd ˈɪŋɡlɪʃ/ 结构化英语 jié gòu huà yīng yǔ
9.2

逐步求精

English

Stepwise refinement 逐步求精 starts with a high-level outline and expands each step until it is small enough to code. For an average of $n$ numbers:

Level 1:

Read in the numbers
Compute the average
Output the average

Level 2:

INPUT n
total ← 0
FOR i ← 1 TO n
    INPUT value
    total ← total + value
NEXT i
average ← total / n
OUTPUT average

Each refinement keeps the previous structure and adds detail.

A six-mark "apply stepwise refinement" question gives you a high-level outline and wants each step expanded into the concrete statements a programmer could code. Keep the steps in the same order, name the data each step reads or produces, and stop when every line is a single input, assignment, output, loop or condition. For example, "validate the password" becomes: input the password; check its length is at least 8; check it contains at least one digit; output "accepted" if both checks pass, otherwise output "rejected".

Stepwise refinement: a Level 1 outline (read in the numbers, compute the average, output the average) is expanded into Level 2 detailed pseudocode with the input loop and the division
Stepwise refinement: expand each high-level step into detailed pseudocode
探索

逐步求精:从提纲到代码

逐层下降。你从一行里的整个任务开始,不断把每个步骤扩展成更小的——直到每个步骤都简单到能直接编码。

词汇 训练
English 中文 拼音
stepwise refinement/ˈstepwaɪz rɪˈfaɪnmənt/ 逐步求精 zhú bù qiú jīng
9.2

逻辑语句

English

A logic statement 逻辑语句 is a Boolean 布尔 condition that controls branching, built from comparisons (x > 10), connectives (AND, OR, NOT) and brackets. Use it as the condition of IF, WHILE or REPEAT...UNTIL:

WHILE attempts < 3 AND NOT loggedIn DO
    INPUT password
    IF password = correctPassword THEN
        loggedIn ← TRUE
    ELSE
        attempts ← attempts + 1
    ENDIF
ENDWHILE

Precedence 优先级 (highest to lowest): NOT, then AND, then OR. Use brackets when unsure. Common mistakes:

  • a = 1 OR 2 is wrong — write a = 1 OR a = 2.
  • NOT a > 5 means NOT (a > 5), i.e. a <= 5.
  • NOT (A AND B) is the same as (NOT A) OR (NOT B) (De Morgan's law 德摩根定律) — handy for simplifying conditions.

Turning a sentence into a logic statement is a skill the papers test directly. "A ticket is free for anyone under 5 or over 65" becomes Age < 5 OR Age > 65. "A mark is valid if it is a whole number from 0 to 100" becomes Mark >= 0 AND Mark <= 100. "The loop stops when the file is finished or ten records have been read" becomes UNTIL EOF(File) OR Count = 10. Write each comparison in full: Age > 65 and Age < 5, never Age > 65 OR < 5.

A parse tree for "attempts < 3 AND NOT loggedIn": NOT applies to loggedIn first, then AND joins that with attempts < 3
Precedence: NOT binds to loggedIn first, then AND combines the two sides

Worked example. Write an identifier table and pseudocode to read 10 numbers and output the largest. The identifier table names each variable with its data type and purpose: Count : INTEGER (loop counter), Num : REAL (the number just read), Max : REAL (largest so far).

INPUT Max
FOR Count ← 2 TO 10
    INPUT Num
    IF Num > Max THEN
        Max ← Num
    ENDIF
NEXT Count
OUTPUT Max

The design decision carrying the marks is initialising Max: it must start lower than any possible input - or, safer still, be set to the first number read. Initialise it to 0 and the algorithm wrongly returns 0 for a list of negative numbers, a bug your trace only exposes if the test data include a negative.

Programming prerequisites for algorithm questions

Before writing or tracing algorithms, use the expression and built-in-function methods on sheets 11.1.1–11.1.2. TO_UPPER and TO_LOWER accept whole strings; UCASE and LCASE in the guide act on a single character. Follow the question's insert.

Join strings with &; convert a number with NUM_TO_STR before joining it. Call a procedure with CALL Name(arguments); use a function as an expression. SETDATE(day, month, year) constructs a DATE value. Check types before evaluation: an invalid expression is ERROR, not a guessed conversion.

For a flowchart with several totals, initialise each accumulator before the loop. Update them on the correct branches, advance the count, then test termination. Put averages after the loop and use the number of values actually included.

词汇 训练
English 中文 拼音
Boolean/ˈbuːlɪən/ 布尔 bù ěr
logic statement/ˈlɒdʒɪk ˈsteɪtmənt/ 逻辑语句 luó jí yǔ jù
precedence/ˈpresɪdəns/ 优先级 yōu xiān jí
De Morgan's law/də ˈmɔːɡənz lɔː/ 德摩根定律 dé mó gēn dìng lǜ
9.2

考官认可的定义

English

A definition question is marked against fixed wording. Learn these exactly, and give one answer only.

Term Definition
abstraction keeping the essential details of a problem and leaving out the details that are not needed
decomposition breaking a problem down into smaller sub-problems, each of which can be solved separately
algorithm a solution to a problem expressed as a sequence of defined steps
identifier table a table listing each identifier used in an algorithm with its data type and a description of its purpose
pseudocode a structured, language-independent way of writing the steps of an algorithm
flowchart a diagram that shows the steps and decisions of an algorithm using standard symbols joined by arrows
sequence statements executed one after another in the order written
selection choosing which statements to execute according to a condition
iteration repeating a group of statements while, or until, a condition holds
stepwise refinement breaking each step of an outline into smaller steps, repeatedly, until each step can be coded directly
logic statement a condition built from comparisons and the operators AND, OR and NOT that evaluates to TRUE or FALSE
9.2

考试技巧

English
  • Define an algorithm as an unambiguous, finite, deterministic sequence of steps, independent of language.
  • Use the three constructs correctly — sequence, selection, iteration — and keep an identifier table with data types.
  • Break a problem down by decomposition and abstraction, then stepwise refinement.
  • Write pseudocode that would actually run: declare variables and follow the exam's pseudocode style.

Common mistakes

  • Using = to assign a value. Assignment is ←; = is a comparison.
  • Forgetting ENDIF, ENDWHILE, ENDCASE or NEXT. Every construct closes, and the closing word is where the mark for the construct is checked.
  • Not initialising a total or counter before the loop, so the algorithm adds to a value that never existed.
  • Using a FOR loop when the number of repetitions is unknown. Reading until a sentinel value or a correct guess needs WHILE or REPEAT ... UNTIL.
  • Writing Age > 65 OR < 5. Each side of OR and AND must be a complete comparison.
  • Answering "explain why decomposition is used" with one benefit written three ways. Three marks need three different benefits.

该知识点的互动课程

逐步完成,配合即时检查练习。

历年真题

更多 A-Level 计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP