Skip to content
Subjects · ⁨科目⁩
  • 1 Style and layout · ⁨书写风格与排版⁩
    1.1

    关键字与大小写

    English

    Pseudocode 伪代码 is the language Cambridge writes algorithms 算法 in. It is not a real programming language — no computer runs it — but the exam marks it as if it were, so the form matters.

    Every keyword 关键字 is written in upper case: IF, REPEAT, PROCEDURE, OUTPUT.

    • Write IF, never if or If.
    • A keyword can never be used as a name of your own: you may not call a variable FOR.

    Common mistakes

    • Lower-case keywords. The mark scheme expects upper case.
    • Inventing keywords. Only the words in this handout are in the syllabus.
    中文

    伪代码(pseudocode)是剑桥书写算法(algorithm)所用的语言。它不是真正的编程语言——没有计算机会运行它——但考试按真代码来评分,所以书写形式很重要。

    每个关键字(keyword)都用大写书写:IF、REPEAT、PROCEDURE、OUTPUT。

    DECLARE Count : INTEGER
    Count ← 3
    IF Count > 0
      THEN
        OUTPUT "Ready"
    ENDIF
    
    • 写 IF,绝不写 if 或 If。
    • 关键字永远不能用作你自己的名字:不能把变量叫做 FOR。

    常见错误

    • 关键字用小写。评分方案要求大写。
    • 自创关键字。只有本讲义中列出的词在考纲之内。
    1.2

    标识符

    English

    An identifier 标识符 is the name you give a variable 变量, a constant 常量, a procedure 过程 or a function 函数.

    Four rules, all from the syllabus:

    • It must start with a capital letter: Count, not count.
    • It may hold only letters and digits — no spaces, no punctuation.
    • It is not case-sensitive 不区分大小写, so Count and COUNT are the same name. Pick one spelling and keep it.
    • Make it mean something. NumberOfPlayers earns the reader's time; N does not.

    Common mistakes

    • count ← 0 — a lower-case start. 0478 requires the capital.
    • Number of players — spaces are not allowed inside a name.
    中文

    标识符(identifier)是你给变量(variable)、常量(constant)、过程(procedure)或函数(function)起的名字。

    DECLARE NumberOfPlayers : INTEGER
    NumberOfPlayers ← 4
    OUTPUT NumberOfPlayers
    

    考纲给出四条规则:

    • 必须以大写字母开头:写 Count,不写 count。
    • 只能包含字母和数字——不能有空格,不能有标点。
    • 不区分大小写,所以 Count 和 COUNT是同一个名字。选定一种写法并保持一致。
    • 名字要有意义。NumberOfPlayers 对得起读者花的时间,N 则不然。

    常见错误

    • count ← 0——以小写开头。0478 要求首字母大写。
    • Number of players——名字内部不允许空格。
    1.3

    注释与缩进

    English

    A comment 注释 starts with // and runs to the end of the line. It is for the human reader; the algorithm ignores it.

    Indentation 缩进 shows which statements are inside a structure. The syllabus asks for four spaces per level, with one exception you must know:

    • THEN and ELSE are indented two spaces from their IF.
    • The statements under them are indented four.
    • ENDIF lines up with its own IF.

    Common mistakes

    • Putting THEN on the IF line. That is the A-Level 9618 layout — see topic 11.
    • No indentation at all. A marker has to see the structure to award the structure marks.
    中文

    注释(comment)以 // 开头,一直到行尾。它写给人看,算法会忽略它。

    // Swap the values of X and Y
    DECLARE X, Y, Temp : INTEGER
    X ← 1
    Y ← 2
    Temp ← X   // temporarily store X
    X ← Y
    Y ← Temp
    OUTPUT X, " ", Y
    

    缩进(indentation)表示哪些语句在某个结构内部。考纲要求每一层四个空格,但有一个你必须记住的例外:

    DECLARE X, Y : INTEGER
    X ← 7
    Y ← 3
    IF X > Y
      THEN
        OUTPUT "X is bigger"
      ELSE
        OUTPUT "Y is bigger or equal"
    ENDIF
    
    • THEN 和 ELSE 相对于它们的 IF 缩进两个空格。
    • 它们下面的语句缩进四个空格。
    • ENDIF 与它自己的 IF 对齐。

    常见错误

    • 把 THEN 写在 IF 那一行。那是 A-Level 9618 的排版——见主题 11。
    • 完全不缩进。评分者必须看得见结构,才能给出结构分。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    pseudocode/ˈsuːdəʊkəʊd/伪代码wěi dài mǎ
    algorithms/ˈælɡərɪθəmz/算法suàn fǎ
    keyword/ˈkiːwɜːd/关键字guān jiàn zì
    identifier/aɪˈdentɪfaɪə/标识符biāo shí fú
    variable/ˈveərɪəbl/变量biàn liàng
    constant/ˈkɒnstənt/常量cháng liàng
    procedure/prəˈsiːdʒə/过程guò chéng
    function/ˈfʌŋkʃn/函数hán shù
    case-sensitive/keɪs ˈsensɪtɪv/不区分大小写bù qū fēn dà xiǎo xiě
    comment/ˈkɒment/注释zhù shì
    indentation/ˌɪndenˈteɪʃn/缩进suō jìn
  • 2 Variables, constants and types · ⁨变量、常量与数据类型⁩
    2.1

    五种数据类型

    English

    0478 pseudocode has exactly five data types 数据类型. Learn the list — naming a type that is not on it loses the mark.

    Type Holds Example
    INTEGER a whole number 整数 42, -7
    REAL a number with a decimal part 小数 3.14, -0.5
    CHAR a single character 单个字符 'A'
    STRING a sequence of characters 字符串 "Hello"
    BOOLEAN TRUE or FALSE 布尔值 TRUE
    • A STRING is written in double quotes, a CHAR in single quotes.
    • TRUE and FALSE are keywords, so they are upper case and carry no quotes.

    Common mistakes

    • Writing FLOAT, DOUBLE or BOOL. Those are real languages, not this syllabus.
    • 'Hello' for a string — single quotes hold one character only.
    中文

    0478 伪代码恰好有五种数据类型(data type)。把这份清单记熟——说出不在清单上的类型会丢分。

    类型 存放 例子
    INTEGER 整数 42、-7
    REAL 带小数部分的数 3.14、-0.5
    CHAR 单个字符 'A'
    STRING 字符串 "Hello"
    BOOLEAN TRUE 或 FALSE TRUE
    DECLARE Age : INTEGER
    DECLARE Price : REAL
    DECLARE Grade : CHAR
    DECLARE Name : STRING
    DECLARE Passed : BOOLEAN
    Age ← 17
    Price ← 2.50
    Grade ← 'A'
    Name ← "Mei"
    Passed ← TRUE
    OUTPUT Name, " is ", Age, " and passed: ", Passed
    
    • STRING 用双引号,CHAR 用单引号。
    • TRUE 和 FALSE 是关键字,所以大写且不加引号。

    常见错误

    • 写 FLOAT、DOUBLE 或 BOOL。那些属于真实的编程语言,不属于本考纲。
    • 用 'Hello' 表示字符串——单引号只装一个字符。
    2.2

    DECLARE · ⁨DECLARE 声明⁩

    English

    DECLARE names a variable 变量 and fixes its type before you use it.

    Several names of one type go on a single line, separated by commas:

    • Declare a variable before its first use, near the top of the algorithm.
    • A variable keeps its type for the whole algorithm — an INTEGER never holds "Mei".

    Common mistakes

    • Leaving out the colon: DECLARE Counter INTEGER.
    • Using a variable that was never declared. The exam expects the declaration.
    中文

    DECLARE 为变量(variable)命名,并在使用之前确定它的类型。

    DECLARE <identifier> : <data type>
    
    DECLARE Counter : INTEGER
    DECLARE TotalToPay : REAL
    Counter ← 1
    TotalToPay ← 19.99
    OUTPUT "Item ", Counter, " costs ", TotalToPay
    

    同一类型的多个名字写在一行,用逗号隔开:

    DECLARE Length, Width, Area : INTEGER
    Length ← 6
    Width ← 4
    Area ← Length * Width
    OUTPUT "Area = ", Area
    
    • 在首次使用之前声明变量,写在算法开头附近。
    • 变量在整个算法中保持它的类型——INTEGER 永远不会装下 "Mei"。

    常见错误

    • 漏掉冒号:DECLARE Counter INTEGER。
    • 使用从未声明过的变量。考试要求写出声明。
    2.3

    CONSTANT · ⁨CONSTANT 常量⁩

    English

    A constant 常量 is a value that is fixed for the whole algorithm — a tax rate, π, the size of a class. Naming it once means a change is made in one place.

    • In 0478 the arrow is used, exactly as for an assignment.
    • The value must be a literal 字面量 — a number, a string, TRUE — never a calculation and never another variable.
    • A constant can never be given a new value later. That is the whole point of it.

    Common mistakes

    • CONSTANT TaxRate = 0.20. The = form is the A-Level 9618 spelling — see topic 11.
    • Assigning to a constant further down the algorithm.
    中文

    常量(constant)是在整个算法中固定不变的值——税率、π、班级人数。命名一次意味着改动只需改一处。

    CONSTANT <identifier> ← <value>
    
    CONSTANT TaxRate ← 0.20
    DECLARE Price, Tax : REAL
    Price ← 50.00
    Tax ← Price * TaxRate
    OUTPUT "Tax to pay: ", Tax
    
    • 在 0478 中使用箭头,与赋值完全一样。
    • 值必须是字面量(literal)——一个数、一个字符串、TRUE——绝不能是计算式,也不能是另一个变量。
    • 常量之后永远不能被赋新值。这正是它存在的意义。

    常见错误

    • CONSTANT TaxRate = 0.20。= 的写法属于 A-Level 9618——见主题 11。
    • 在算法后面给常量赋值。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    data types/ˈdeɪtə taɪps/数据类型shù jù lèi xíng
    whole number/həʊl ˈnʌmbə/整数zhěng shù
    decimal part/ˈdesɪml pɑːt/小数xiǎo shù
    single character/ˈsɪŋɡl ˈkærɪktə/单个字符dān gè zì fú
    sequence of characters/ˈsiːkwəns ɒv ˈkærɪktəz/字符串zì fú chuàn
    TRUE` or `FALSE布尔值bù ěr zhí
    variable/ˈveərɪəbl/变量biàn liàng
    constant/ˈkɒnstənt/常量cháng liàng
    literal/ˈlɪtərəl/字面量zì miàn liàng
  • 3 Assignment, input and output · ⁨赋值、输入与输出⁩
    3.1

    赋值箭头

    English

    The assignment 赋值 operator is ←, a left-pointing arrow. It means take the value on the right and put it in the box on the left.

    Counter ← Counter + 1 looks impossible as mathematics and is ordinary as an instruction: work out the right-hand side with the value the box holds now, then store the result back.

    • If you cannot type ←, write <-. Both are accepted, here and in the exam.
    • The left side must be a single identifier or one array element. Never a calculation.

    Common mistakes

    • Counter = 0. In pseudocode = is a comparison, not an assignment — and confusing the two is the single commonest syntax error in this paper.
    • Counter + 1 ← Counter. The arrow points at the thing being changed.
    中文

    赋值(assignment)运算符是 ←,一个向左的箭头。它的意思是把右边的值放进左边的盒子里。

    <identifier> ← <value>
    
    DECLARE Counter : INTEGER
    Counter ← 0
    Counter ← Counter + 1
    Counter ← Counter + 1
    OUTPUT Counter
    

    Counter ← Counter + 1 作为数学式看似不可能,作为指令却再平常不过:用盒子当前装的值算出右边,再把结果存回去。

    • 如果打不出 ←,就写 <-。两者都被接受,本站和考试都一样。
    • 左边必须是单个标识符或一个数组元素,绝不能是计算式。

    常见错误

    • Counter = 0。在伪代码中 = 是比较,不是赋值——混淆两者是本卷最常见的语法错误。
    • Counter + 1 ← Counter。箭头指向被改变的那个东西。
    3.2

    INPUT 与 OUTPUT

    English

    INPUT reads a value from the user into a variable. OUTPUT displays one or more values.

    • INPUT takes exactly one variable, and that variable must already be declared.
    • OUTPUT takes any number of items separated by commas; they are printed one after another with nothing between them.
    • A literal 字面量 string in an OUTPUT goes in double quotes; a variable does not.

    Prompting the user

    An INPUT on its own shows nothing on screen, so a well-written algorithm prints a prompt 提示 first:

    Common mistakes

    • INPUT "Enter a number", X — the prompt is a separate OUTPUT statement.
    • OUTPUT "Total: " + Total. 0478 joins output items with a comma; + is arithmetic and & belongs to A-Level 9618 (topic 11).
    • Forgetting the quotes: OUTPUT Hello looks for a variable called Hello.
    中文

    INPUT 从用户读入一个值到变量中。OUTPUT 显示一个或多个值。

    DECLARE Name : STRING
    DECLARE Age : INTEGER
    INPUT Name
    INPUT Age
    OUTPUT "Hello ", Name
    OUTPUT "Next year you will be ", Age + 1
    
    • INPUT 恰好接受一个变量,且该变量必须已经声明。
    • OUTPUT 接受任意多项,用逗号分隔;它们依次输出,中间不加任何东西。
    • OUTPUT 中的字面量(literal)字符串加双引号,变量不加。

    提示用户

    单独的 INPUT 在屏幕上什么也不显示,所以写得好的算法会先输出一句提示(prompt):

    DECLARE Radius : REAL
    OUTPUT "Enter the radius: "
    INPUT Radius
    OUTPUT "The diameter is ", Radius * 2
    

    常见错误

    • INPUT "Enter a number", X——提示是一条单独的 OUTPUT 语句。
    • OUTPUT "Total: " + Total。0478 用逗号连接输出项;+ 是算术运算,而 & 属于 A-Level 9618(主题 11)。
    • 漏掉引号:OUTPUT Hello 会去找一个叫 Hello 的变量。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    assignment/əˈsaɪnmənt/赋值fù zhí
    literal/ˈlɪtərəl/字面量zì miàn liàng
    prompt/prɒmpt/提示tí shì
  • 4 Arithmetic and logic · ⁨算术与逻辑⁩
    4.1

    算术运算符

    English

    Five arithmetic 算术 operators, in the order a calculator uses them.

    Operator Meaning A is 7, B is 2
    + add 加 A + B is 9
    - subtract 减 A - B is 5
    * multiply 乘 A * B is 14
    / divide 除 A / B is 3.5
    ^ raise to a power 幂 A ^ B is 49

    Brackets come first, then ^, then * and /, then + and - — the usual precedence 优先级. Use brackets whenever the reader would have to stop and think.

    Common mistakes

    • Expecting / to give a whole number. 7 / 2 is 3.5, not 3; for a whole number use DIV.
    • Writing A x B or A ÷ B. Use * and /.
    中文

    五个算术(arithmetic)运算符,按计算器使用它们的顺序排列。

    运算符 含义 A 为 7,B 为 2
    + 加 A + B 得 9
    - 减 A - B 得 5
    * 乘 A * B 得 14
    / 除 A / B 得 3.5
    ^ 幂 A ^ B 得 49
    DECLARE A, B : INTEGER
    A ← 7
    B ← 2
    OUTPUT "Sum: ", A + B
    OUTPUT "Product: ", A * B
    OUTPUT "Quotient: ", A / B
    OUTPUT "Power: ", A ^ B
    

    先算括号,再算 ^,然后是 * 和 /,最后是 + 和 -——通常的优先级(precedence)。只要读者需要停下来想一想,就加括号。

    DECLARE Total : REAL
    Total ← (12 + 18) / 2
    OUTPUT "Mean: ", Total
    

    常见错误

    • 以为 / 会给出整数。7 / 2 是 3.5,不是 3;要整数请用 DIV。
    • 写成 A x B 或 A ÷ B。请用 * 和 /。
    4.2

    DIV 与 MOD

    English

    Integer division 整数除法 answers two different questions, and 0478 writes each of them as a function 函数, with the two values in brackets.

    • DIV(a, b) — how many whole times b goes into a, the quotient 商.
    • MOD(a, b) — what is left over, the remainder 余数.

    Both take integers, and both return an integer.

    What they are for

    MOD is the standard test for divides exactly, which makes it the way to ask whether a number is even 偶数:

    DIV converts a total into whole units — seconds into minutes, pence into pounds:

    Common mistakes

    • 10 MOD 3. That is the A-Level 9618 form; 0478 uses the function form MOD(10, 3).
    • Mixing the two up. DIV gives the whole part; MOD gives what does not fit.
    中文

    整数除法(integer division)回答两个不同的问题,而 0478 把它们各写成一个函数(function),两个值放在括号里。

    • DIV(a, b)——b 能整着进入 a 多少次,即商(quotient)。
    • MOD(a, b)——剩下多少,即余数(remainder)。
    OUTPUT DIV(10, 3)
    OUTPUT MOD(10, 3)
    OUTPUT DIV(17, 5)
    OUTPUT MOD(17, 5)
    

    两者都接受整数,也都返回整数。

    它们的用途

    MOD 是"能否整除"的标准检验,因而也是判断一个数是否为偶数的方法:

    DECLARE Number : INTEGER
    Number ← 12
    IF MOD(Number, 2) = 0
      THEN
        OUTPUT Number, " is even"
      ELSE
        OUTPUT Number, " is odd"
    ENDIF
    

    DIV 把总量换算成整单位——秒换分钟,便士换英镑:

    DECLARE Seconds : INTEGER
    Seconds ← 200
    OUTPUT DIV(Seconds, 60), " minutes and ", MOD(Seconds, 60), " seconds"
    

    常见错误

    • 10 MOD 3。那是 A-Level 9618 的写法;0478 使用函数形式 MOD(10, 3)。
    • 把两者弄混。DIV 给出整数部分;MOD 给出装不下的部分。
    4.3

    关系运算符与逻辑运算符

    English

    A relational operator 关系运算符 compares two values and produces TRUE or FALSE.

    Operator Means
    = is equal to 等于
    <> is not equal to 不等于
    > is greater than 大于
    < is less than 小于
    >= is greater than or equal to 大于等于
    <= is less than or equal to 小于等于

    The three logic operators 逻辑运算符 join conditions:

    • AND — both sides must be TRUE.
    • OR — at least one side must be TRUE.
    • NOT — turns TRUE into FALSE and back.

    Common mistakes

    • <> is the not equal sign here — not !=, which belongs to other languages.
    • IF Age >= 15 AND <= 18. Each side of AND needs its own complete comparison: Age >= 15 AND Age <= 18.
    • Calling these comparison operators in an answer. The syllabus term is relational.
    中文

    关系运算符(relational operator)比较两个值,产生 TRUE 或 FALSE。

    运算符 含义
    = 等于
    <> 不等于
    > 大于
    < 小于
    >= 大于等于
    <= 小于等于
    DECLARE Mark : INTEGER
    Mark ← 55
    OUTPUT "Pass: ", Mark >= 50
    OUTPUT "Perfect: ", Mark = 100
    OUTPUT "Not zero: ", Mark <> 0
    

    三个逻辑运算符(logic operator)把条件连接起来:

    • AND——两边都必须为 TRUE。
    • OR——至少一边为 TRUE。
    • NOT——把 TRUE 变成 FALSE,反之亦然。
    DECLARE Age : INTEGER
    DECLARE HasTicket : BOOLEAN
    Age ← 16
    HasTicket ← TRUE
    IF Age >= 15 AND HasTicket = TRUE
      THEN
        OUTPUT "Admitted"
    ENDIF
    IF NOT (Age > 18)
      THEN
        OUTPUT "Still a student rate"
    ENDIF
    

    常见错误

    • 这里的不等于写作 <>,而不是属于其他语言的 !=。
    • IF Age >= 15 AND <= 18。AND 的每一边都需要完整的比较:Age >= 15 AND Age <= 18。
    • 在答卷中称它们为比较运算符。考纲用语是关系运算符。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    arithmetic/əˈrɪθmətɪk/算术suàn shù
    add/æd/加jiā
    subtract/sʌbˈtrækt/减jiǎn
    multiply/ˌmʌltɪˈplaɪ/乘chéng
    divide/dɪˈvaɪd/除chú
    raise to a power/reɪz tʊ ə ˈpaʊə/幂mì
    precedence/ˈpresɪdəns/优先级yōu xiān jí
    Integer division/ˈɪntɪdʒə dɪˈvɪʒn/整数除法zhěng shù chú fǎ
    function/ˈfʌŋkʃn/函数hán shù
    quotient/ˈkwəʊʃənt/商shāng
    remainder/rɪˈmeɪndə/余数yú shù
    even/ˈiːvən/偶数ǒu shù
    relational operator/rɪˈleɪʃənl ˈɒpəreɪtə/关系运算符guān xì yùn suàn fú
    is equal to/ɪz ˈiːkwl tuː/等于děng yú
    is not equal to/ɪz nɒt ˈiːkwl tuː/不等于bù děng yú
    is greater than/ɪz ˈɡreɪtə ðən/大于dà yú
    is less than/ɪz les ðən/小于xiǎo yú
    is greater than or equal to/ɪz ˈɡreɪtə ðən ɔː ˈiːkwl tuː/大于等于dà yú děng yú
    is less than or equal to/ɪz les ðən ɔː ˈiːkwl tuː/小于等于xiǎo yú děng yú
    logic operators/ˈlɒdʒɪk ˈɒpəreɪtəz/逻辑运算符luó jí yùn suàn fú
  • 5 String operations · ⁨字符串操作⁩
    5.1

    LENGTH、UCASE 与 LCASE

    English

    0478 publishes four string 字符串 routines and no others. Three of them are here.

    LENGTH(<identifier>) returns how many characters 字符 a string holds — spaces included.

    UCASE(<identifier>) returns the string in upper case 大写, LCASE(<identifier>) in lower case 小写. Neither changes the original 原值 — each hands back a new value.

    That last line still prints Happy: to keep the change you must assign it back.

    Comparing without worrying about case

    UCASE on both sides is the standard way to accept an answer however it was typed:

    Common mistakes

    • Expecting UCASE(Name) to change Name. Assign the result back.
    • LENGTH counts characters, not words. LENGTH("Happy Days") is 10.
    中文

    0478 只公布四个字符串(string)例程,没有别的。其中三个在这里。

    LENGTH(<identifier>) 返回字符串含有多少个字符(character)——空格也算。

    OUTPUT LENGTH("Happy Days")
    OUTPUT LENGTH("")
    

    UCASE(<identifier>) 返回大写形式,LCASE(<identifier>) 返回小写形式。两者都不改变原值(original)——各自交回一个新值。

    DECLARE Name : STRING
    Name ← "Happy"
    OUTPUT UCASE(Name)
    OUTPUT LCASE(Name)
    OUTPUT Name
    

    最后那一行仍然输出 Happy:要保留改动,必须把结果赋回去。

    DECLARE Name : STRING
    Name ← "Happy"
    Name ← UCASE(Name)
    OUTPUT Name
    

    比较时不必顾虑大小写

    两边都套 UCASE,是接受任意大小写输入的标准做法:

    DECLARE Answer : STRING
    Answer ← "yes"
    IF UCASE(Answer) = "YES"
      THEN
        OUTPUT "Accepted"
    ENDIF
    

    常见错误

    • 以为 UCASE(Name) 会改变 Name。请把结果赋回去。
    • LENGTH 数的是字符,不是单词。LENGTH("Happy Days") 是 10。
    5.2

    SUBSTRING · ⁨SUBSTRING 取子串⁩

    English

    SUBSTRING(<identifier>, <start>, <length>) pulls a piece out of a string — starting at position start, taking length characters.

    ⚠️ Counting starts at 1, not 0. The first character of "Happy Days" is at position 1.

    Taking one character, and the rest

    LENGTH inside SUBSTRING is what makes the last two lines work for a word of any size — hard-coding 8 would break the moment the word changed.

    Reading a string one character at a time

    Common mistakes

    • Starting at 0. Position 1 is the first character.
    • Reading the third argument as an end position. It is a count — SUBSTRING(W, 2, 3) takes three characters beginning at the second.
    • Asking for more characters than the string has.
    中文

    SUBSTRING(<identifier>, <start>, <length>) 从字符串中取出一段——从位置 start 开始,取 length 个字符。

    OUTPUT SUBSTRING("Happy Days", 1, 5)
    OUTPUT SUBSTRING("Happy Days", 7, 4)
    

    ⚠️ 计数从 1 开始,不是 0。"Happy Days" 的第一个字符在位置 1。

    取一个字符,以及取剩下的部分

    DECLARE Word : STRING
    Word ← "Computer"
    OUTPUT "First letter: ", SUBSTRING(Word, 1, 1)
    OUTPUT "Last letter: ", SUBSTRING(Word, LENGTH(Word), 1)
    OUTPUT "Without the first: ", SUBSTRING(Word, 2, LENGTH(Word) - 1)
    

    把 LENGTH 套进 SUBSTRING,正是后两行对任意长度的词都成立的原因——写死 8 的话,词一变就错。

    逐字符读取字符串

    DECLARE Word : STRING
    DECLARE Index : INTEGER
    Word ← "Cat"
    FOR Index ← 1 TO LENGTH(Word)
        OUTPUT SUBSTRING(Word, Index, 1)
    NEXT Index
    

    常见错误

    • 从 0 开始。位置 1 才是第一个字符。
    • 把第三个参数当成结束位置。它是一个个数——SUBSTRING(W, 2, 3) 从第二个字符起取三个。
    • 要求的字符数超过字符串本身的长度。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    string/strɪŋ/字符串zì fú chuàn
    characters/ˈkærɪktəz/字符zì fú
    upper case/ˈʌpə keɪs/大写dà xiě
    lower case/ˈləʊə keɪs/小写xiǎo xiě
    original/əˈrɪdʒɪnl/原值yuán zhí
  • 6 Selection · ⁨选择结构⁩
    6.1

    IF、THEN、ELSE、ENDIF

    English

    Selection 选择 runs one group of statements or another, depending on a condition 条件.

    Add ELSE for the other case. Exactly one of the two branches 分支 runs — never both, never neither.

    The layout is the one part students lose marks on, so learn it as a shape:

    • IF and its condition on one line, nothing after the condition.
    • THEN and ELSE on their own lines, indented two spaces.
    • The statements indented four.
    • ENDIF back at the column of its IF.

    Nesting 嵌套

    An IF inside an IF handles more than two outcomes. Each one needs its own ENDIF.

    Common mistakes

    • Forgetting ENDIF. Every IF closes, and a missing one is a syntax error 语法错误 the marker will see at a glance.
    • IF Mark >= 50 THEN OUTPUT "Pass" on one line. No such form exists in either syllabus; write the three lines.
    • IF Mark = 50 THEN written as IF Mark ← 50. The arrow assigns; = compares.
    中文

    选择(selection)根据一个条件(condition)运行这一组语句或那一组。

    IF <condition>
      THEN
        <statements>
    ENDIF
    
    DECLARE Mark : INTEGER
    Mark ← 72
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
    ENDIF
    

    加上 ELSE 处理另一种情况。两个分支(branch)中恰好运行一个——绝不会两个都运行,也绝不会一个都不运行。

    DECLARE Mark : INTEGER
    Mark ← 41
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
      ELSE
        OUTPUT "Fail"
    ENDIF
    

    排版是学生最常丢分的地方,所以把它当作一个图形记下来:

    • IF 和它的条件写在一行,条件后面什么都不写。
    • THEN 和 ELSE 各占一行,缩进两个空格。
    • 语句缩进四个空格。
    • ENDIF 回到它自己 IF 所在的列。

    嵌套

    IF 里面再放 IF,可以处理超过两种结果。每一个都需要自己的 ENDIF。

    DECLARE Mark : INTEGER
    Mark ← 85
    IF Mark >= 80
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Mark >= 50
          THEN
            OUTPUT "Pass"
          ELSE
            OUTPUT "Fail"
        ENDIF
    ENDIF
    

    常见错误

    • 忘记 ENDIF。每个 IF 都要闭合,少一个就是语法错误(syntax error),评分者一眼就能看出。
    • 把 IF Mark >= 50 THEN OUTPUT "Pass" 写成一行。两份考纲都没有这种写法;请写成三行。
    • 把 IF Mark = 50 THEN 写成 IF Mark ← 50。箭头是赋值,= 才是比较。
    6.2

    CASE OF · ⁨CASE OF 多分支⁩

    English

    When one variable is tested against several single values, CASE OF says it far more clearly than a stack of nested IFs.

    • Each branch is a value, a colon, then what to do.
    • OTHERWISE catches everything the listed values missed. It is optional, and writing one is good practice — it is what happens when the user types something unexpected.
    • The first matching branch runs, and the rest are skipped.

    A range, and a character

    Common mistakes

    • Using CASE OF for a condition. It tests one variable against values; Mark >= 50 needs an IF.
    • Forgetting ENDCASE.
    • Leaving out OTHERWISE and then wondering why an unexpected value does nothing at all.
    中文

    当一个变量要与若干单个值逐一比较时,CASE OF 比一叠嵌套的 IF 清楚得多。

    CASE OF <identifier>
        <value 1> : <statement>
        <value 2> : <statement>
        OTHERWISE <statement>
    ENDCASE
    
    DECLARE Choice : INTEGER
    Choice ← 2
    CASE OF Choice
        1 : OUTPUT "You chose north"
        2 : OUTPUT "You chose south"
        3 : OUTPUT "You chose east"
        4 : OUTPUT "You chose west"
        OTHERWISE OUTPUT "That is not a direction"
    ENDCASE
    
    • 每个分支是一个值、一个冒号,然后是要做的事。
    • OTHERWISE 兜住所列值没有覆盖到的一切。它是可选的,写上是好习惯——用户输入意料之外的东西时,走的就是它。
    • 第一个匹配的分支运行,其余的跳过。

    一个范围,和一个字符

    DECLARE Grade : CHAR
    Grade ← 'B'
    CASE OF Grade
        'A' : OUTPUT "Excellent"
        'B' : OUTPUT "Good"
        'C' : OUTPUT "Satisfactory"
        OTHERWISE OUTPUT "Unclassified"
    ENDCASE
    

    常见错误

    • 用 CASE OF 处理条件。它把一个变量与若干值比较;Mark >= 50 需要 IF。
    • 忘记 ENDCASE。
    • 省略 OTHERWISE,然后困惑于意料之外的值为什么毫无反应。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    Selection/sɪˈlekʃn/选择xuǎn zé
    condition/kənˈdɪʃn/条件tiáo jiàn
    branches/ˈbræntʃɪz/分支fēn zhī
    Nesting/ˈnestɪŋ/嵌套qiàn tào
    syntax error/ˈsɪntæks ˈerə/语法错误yǔ fǎ cuò wù
  • 7 Iteration · ⁨循环结构⁩
    7.1

    FOR 计数循环

    English

    Iteration 迭代 repeats statements. Use a FOR loop when you know before you start how many times — a count-controlled 计数控制 loop.

    The counter 计数器 starts at the first value, and the loop runs once for every value up to and including the second. 1 TO 5 runs five times.

    STEP

    STEP changes the size of each jump. A negative step counts down.

    Running totals

    The commonest use: a variable outside the loop that the loop adds to.

    Total ← 0 must sit before the loop. Inside, it would reset on every pass.

    Common mistakes

    • NEXT naming the wrong counter. Nested loops must close in the reverse order they opened: the inner NEXT first.
    • Assuming 1 TO 5 runs four times. Both ends are included.
    • Changing the counter inside the loop. Let FOR own it.
    中文

    迭代(iteration)重复执行语句。当你在开始之前就知道要重复多少次时,使用 FOR 循环——计数控制(count-controlled)循环。

    FOR <identifier> ← <value1> TO <value2>
        <statements>
    NEXT <identifier>
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 5
        OUTPUT "Line ", Index
    NEXT Index
    

    计数器(counter)从第一个值开始,循环对直到第二个值(包含它)的每个值各运行一次。1 TO 5 运行五次。

    STEP

    STEP 改变每次跳跃的大小。负的步长会倒着数。

    DECLARE Index : INTEGER
    FOR Index ← 2 TO 10 STEP 2
        OUTPUT Index
    NEXT Index
    FOR Index ← 3 TO 1 STEP -1
        OUTPUT "Countdown ", Index
    NEXT Index
    

    累加总和

    最常见的用法:循环之外有一个变量,循环不断往里加。

    DECLARE Index, Total : INTEGER
    Total ← 0
    FOR Index ← 1 TO 10
        Total ← Total + Index
    NEXT Index
    OUTPUT "Sum of 1 to 10 is ", Total
    

    Total ← 0 必须写在循环之前。写在里面,它每一轮都会被清零。

    常见错误

    • NEXT 写错了计数器。嵌套循环必须按打开的相反顺序闭合:先写内层的 NEXT。
    • 以为 1 TO 5 运行四次。两端都包含。
    • 在循环内部改动计数器。让 FOR 自己掌管它。
    7.2

    WHILE 前条件循环

    English

    A WHILE loop tests before each pass, so it can run zero times. Use it when the number of repeats depends on something that happens while the loop runs.

    Something inside the loop must eventually make the condition false, or the loop never ends — an infinite loop 无限循环.

    Common mistakes

    • Forgetting to change the variable the condition tests, giving an infinite loop.
    • Leaving out DO or ENDWHILE.
    • Using WHILE where the count is known. A FOR says what you mean in one line.
    中文

    WHILE 循环在每一轮之前检验,因此它可能运行零次。当重复次数取决于循环运行中发生的事情时,用它。

    WHILE <condition> DO
        <statements>
    ENDWHILE
    
    DECLARE Total : INTEGER
    Total ← 1
    WHILE Total < 100 DO
        Total ← Total * 2
    ENDWHILE
    OUTPUT "First power of two past 100: ", Total
    

    循环内部必须有东西最终使条件变为假,否则循环永不结束——这就是无限循环(infinite loop)。

    DECLARE Count : INTEGER
    Count ← 5
    WHILE Count > 0 DO
        OUTPUT Count
        Count ← Count - 1
    ENDWHILE
    OUTPUT "Lift off"
    

    常见错误

    • 忘记改动条件所检验的变量,造成无限循环。
    • 漏掉 DO 或 ENDWHILE。
    • 在次数已知时用 WHILE。FOR 一行就把意思说清楚了。
    7.3

    REPEAT 后条件循环

    English

    A REPEAT loop tests after each pass, so it always runs at least once.

    That "at least once" is the reason to choose it: validating 验证 input, where you must ask before you can judge the answer.

    ⚠️ UNTIL states the condition that stops the loop; WHILE states the one that keeps it going. They are opposites, and swapping them is the classic error.

    Tests Runs at least once? Condition means
    FOR a counter no (an empty range runs zero times) —
    WHILE before no keep going while this is true
    REPEAT after yes stop when this becomes true

    Common mistakes

    • Writing UNTIL Number < 100 when you mean UNTIL Number >= 100.
    • Using REPEAT where the body must be able to run zero times.
    • Forgetting that UNTIL ends the structure — there is no ENDREPEAT.
    中文

    REPEAT 循环在每一轮之后检验,因此它总是至少运行一次。

    REPEAT
        <statements>
    UNTIL <condition>
    

    "至少一次"正是选择它的理由:验证(validating)输入时,你必须先问,才能判断答案。

    DECLARE Number : INTEGER
    Number ← 0
    REPEAT
        Number ← Number + 25
        OUTPUT "Trying ", Number
    UNTIL Number >= 100
    OUTPUT "Reached ", Number
    

    ⚠️ UNTIL 陈述的是停止循环的条件;WHILE 陈述的是继续循环的条件。两者相反,弄反了是经典错误。

    何时检验 至少运行一次? 条件的含义
    FOR 看计数器 否(空区间运行零次) —
    WHILE 之前 否 为真时继续
    REPEAT 之后 是 变为真时停止

    常见错误

    • 想写 UNTIL Number >= 100 却写成 UNTIL Number < 100。
    • 在循环体必须能运行零次的场合用 REPEAT。
    • 忘记 UNTIL 就是结构的结尾——没有 ENDREPEAT 这种写法。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    Iteration/ˌɪtəˈreɪʃn/迭代dié dài
    count-controlled/kaʊnt kənˈtrəʊld/计数控制jì shù kòng zhì
    counter/ˈkaʊntə/计数器jì shù qì
    infinite loop/ˈɪnfɪnət luːp/无限循环wú xiàn xún huán
    validating/ˈvælɪdeɪtɪŋ/验证yàn zhèng
  • 8 Arrays · ⁨数组⁩
    8.1

    一维数组

    English

    An array 数组 holds many values of one type under one name. Each value sits at an index 下标.

    • The bounds 边界 are written lower:upper, and both are included — [1:3] has three elements 元素.
    • Cambridge arrays normally start at 1, not 0.
    • Every element has the same type, fixed by OF.

    Filling and reading with a FOR loop

    An array and a counted loop belong together: the counter is the index.

    Finding the largest

    Start Largest at the first element, never at 0 — with negative data, 0 would win and the answer would be wrong.

    Common mistakes

    • Reading Scores[6] from an array declared [1:5]. That is out of bounds 越界.
    • Writing Scores(3). Arrays use square brackets; round brackets call a function.
    • Declaring [1:5] and then looping 0 TO 4.
    中文

    数组(array)在一个名字下存放同一类型的多个值。每个值位于一个下标(index)上。

    DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>
    
    DECLARE Names : ARRAY[1:3] OF STRING
    Names[1] ← "Mei"
    Names[2] ← "Sam"
    Names[3] ← "Ana"
    OUTPUT Names[2]
    
    • 边界(bound)写作 lower:upper,而且两端都包含——[1:3] 有三个元素(element)。
    • 剑桥的数组通常从 1 开始,不是 0。
    • 每个元素的类型相同,由 OF 确定。

    用 FOR 循环填充与读取

    数组和计数循环天生一对:计数器就是下标。

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Total : INTEGER
    FOR Index ← 1 TO 5
        Scores[Index] ← Index * 10
    NEXT Index
    Total ← 0
    FOR Index ← 1 TO 5
        Total ← Total + Scores[Index]
    NEXT Index
    OUTPUT "Total: ", Total
    OUTPUT "Mean: ", Total / 5
    

    找出最大值

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Largest : INTEGER
    Scores[1] ← 42
    Scores[2] ← 17
    Scores[3] ← 93
    Scores[4] ← 8
    Scores[5] ← 55
    Largest ← Scores[1]
    FOR Index ← 2 TO 5
        IF Scores[Index] > Largest
          THEN
            Largest ← Scores[Index]
        ENDIF
    NEXT Index
    OUTPUT "Largest: ", Largest
    

    把 Largest 初始化为第一个元素,绝不要用 0——遇到负数数据时,0 会胜出,答案就错了。

    常见错误

    • 从声明为 [1:5] 的数组中读 Scores[6],这是越界(out of bounds)。
    • 写成 Scores(3)。数组用方括号;圆括号是调用函数。
    • 声明 [1:5] 却循环 0 TO 4。
    8.2

    二维数组

    English

    A 2-D array 二维数组 is a table: rows and columns, two indexes.

    The first index is the row 行, the second the column 列.

    Nested loops walk a table

    One loop per dimension 维度. The inner loop finishes a whole row before the outer moves on.

    ⚠️ The inner NEXT closes the inner counter. NEXT Row before NEXT Col crosses the loops over and is nonsense — a marker spots it instantly.

    Common mistakes

    • Swapping row and column. Grid[2,3] is row 2, column 3.
    • Grid[Row][Col]. Cambridge writes one pair of brackets with a comma inside.
    • Crossing the NEXT lines over, as above.
    中文

    二维数组(2-D array)是一张表:有行有列,两个下标。

    DECLARE <identifier> : ARRAY[<lower1>:<upper1>, <lower2>:<upper2>] OF <data type>
    
    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    Grid[1,1] ← 1
    Grid[1,2] ← 2
    Grid[1,3] ← 3
    Grid[2,1] ← 4
    Grid[2,2] ← 5
    Grid[2,3] ← 6
    OUTPUT Grid[2,3]
    

    第一个下标是行(row),第二个是列(column)。

    嵌套循环遍历表格

    每个维度(dimension)一层循环。内层循环走完一整行,外层才前进一步。

    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    DECLARE Row, Col : INTEGER
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            Grid[Row, Col] ← Row * Col
        NEXT Col
    NEXT Row
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            OUTPUT "Grid[", Row, ",", Col, "] = ", Grid[Row, Col]
        NEXT Col
    NEXT Row
    

    ⚠️ 内层的 NEXT 闭合内层计数器。把 NEXT Row 写在 NEXT Col 之前就把两层循环交叉了,毫无意义——评分者一眼就看得出来。

    常见错误

    • 把行和列弄反。Grid[2,3] 是第 2 行、第 3 列。
    • 写成 Grid[Row][Col]。剑桥写一对方括号,里面用逗号。
    • 如上所述把 NEXT 两行交叉。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    array/əˈreɪ/数组shù zǔ
    index/ˈɪndeks/下标xià biāo
    bounds/baʊndz/边界biān jiè
    elements/ˈelɪmənts/元素yuán sù
    out of bounds/ˈaʊtəv baʊndz/越界yuè jiè
    2-D array/tuː diː əˈreɪ/二维数组èr wéi shù zǔ
    row/rəʊ/行xíng
    column/ˈkɒlʌm/列liè
    dimension/daɪˈmenʃn/维度wéi dù
  • 9 Procedures and functions · ⁨过程与函数⁩
    9.1

    PROCEDURE 与 CALL

    English

    A procedure 过程 is a named block of statements. Writing one once and calling it from several places is decomposition 分解 — the idea the whole of paper 2 rests on.

    A procedure is called by name, with the keyword CALL:

    • The definition 定义 does nothing on its own. Only CALL runs it.
    • Control returns to the line after the CALL when the procedure ends.
    • A procedure does not give a value back. If you need one, you want a function.

    Common mistakes

    • Writing DefaultLine on its own to run it. 0478 requires CALL.
    • Leaving out ENDPROCEDURE.
    • Expecting the procedure's own variables to exist outside it.
    中文

    过程(procedure)是一段有名字的语句块。写一次、在多处调用,就是分解(decomposition)——整张试卷二都建立在这个思想上。

    PROCEDURE <identifier>
        <statements>
    ENDPROCEDURE
    

    过程通过名字被调用,要用关键字 CALL:

    PROCEDURE DefaultLine
        OUTPUT "------------------------------"
    ENDPROCEDURE
    
    CALL DefaultLine
    OUTPUT "Report"
    CALL DefaultLine
    
    • 定义(definition)本身什么也不做。只有 CALL 才会运行它。
    • 过程结束后,控制权回到 CALL 的下一行。
    • 过程不返回值。需要返回值时,你要的是函数。

    常见错误

    • 只写 DefaultLine 就想运行它。0478 要求写 CALL。
    • 漏掉 ENDPROCEDURE。
    • 以为过程内部的变量在外面还存在。
    9.2

    FUNCTION 与 RETURN

    English

    A function 函数 is a procedure that hands a value back. It is written where that value is needed — inside an OUTPUT, on the right of an assignment, inside a condition.

    • RETURNS <data type> on the header says what type comes back. It is not optional.
    • RETURN ends the function immediately — nothing after it runs.
    • A function is never called with CALL; it is used wherever its value belongs.

    A function inside a condition

    Common mistakes

    • CALL SumSquare(10, 20) — that throws the answer away.
    • A function with no RETURN on some path. Every route out must return a value.
    • Leaving RETURNS INTEGER off the header.
    中文

    函数(function)是会交回一个值的过程。它写在需要那个值的地方——OUTPUT 里面、赋值号右边、条件里面。

    FUNCTION <identifier>(<parameters>) RETURNS <data type>
        <statements>
        RETURN <value>
    ENDFUNCTION
    
    FUNCTION SumSquare(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
        RETURN Number1 * Number1 + Number2 * Number2
    ENDFUNCTION
    
    OUTPUT "Sum of squares = ", SumSquare(10, 20)
    
    • 头部的 RETURNS <data type> 说明返回什么类型。它不是可选的。
    • RETURN 立即结束函数——它后面的语句都不会运行。
    • 函数绝不用 CALL 调用;它出现在它的值该出现的地方。

    把函数写进条件里

    FUNCTION IsEven(Number : INTEGER) RETURNS BOOLEAN
        RETURN MOD(Number, 2) = 0
    ENDFUNCTION
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 6
        IF IsEven(Index)
          THEN
            OUTPUT Index, " is even"
        ENDIF
    NEXT Index
    

    常见错误

    • CALL SumSquare(10, 20)——那把答案扔掉了。
    • 某条路径上没有 RETURN 的函数。每一条出口都必须返回一个值。
    • 头部漏写 RETURNS INTEGER。
    9.3

    参数

    English

    A parameter 参数 is a value a procedure or function is given when it is called. Each one carries its own type.

    Several parameters are separated by commas, and the order at the call must match the order in the definition:

    ⚠️ In 0478 every parameter is passed by value 传值: the procedure works on a copy, so changing it inside changes nothing outside. To get a value back, use a FUNCTION and RETURN it. (A-Level 9618 adds BYREF for the other behaviour — topic 11.)

    Common mistakes

    • PROCEDURE Line(Size) with no type.
    • Calling with the arguments in the wrong order — Greet(2, "Mei") is a type error.
    • Expecting a procedure to change the variable you passed in. In 0478 it cannot.
    中文

    参数(parameter)是调用过程或函数时交给它的值。每个参数都带自己的类型。

    PROCEDURE Line(Size : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Size
            OUTPUT "-"
        NEXT Index
    ENDPROCEDURE
    
    CALL Line(5)
    CALL Line(20)
    

    多个参数用逗号分隔,调用时的顺序必须与定义时一致:

    PROCEDURE Greet(Name : STRING, Times : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Times
            OUTPUT "Hello ", Name
        NEXT Index
    ENDPROCEDURE
    
    CALL Greet("Mei", 2)
    CALL Greet("Sam", 1)
    

    ⚠️ 在 0478 中每个参数都按值传递(passed by value):过程处理的是一个副本,所以在里面改动它,外面毫无变化。要取回一个值,请用 FUNCTION 并 RETURN 它。(A-Level 9618 增加了 BYREF 来实现另一种行为——主题 11。)

    FUNCTION Doubled(Number : INTEGER) RETURNS INTEGER
        RETURN Number * 2
    ENDFUNCTION
    
    DECLARE Value : INTEGER
    Value ← 7
    Value ← Doubled(Value)
    OUTPUT Value
    

    常见错误

    • PROCEDURE Line(Size),没有写类型。
    • 调用时参数顺序错了——Greet(2, "Mei") 是类型错误。
    • 指望过程去改变你传进去的变量。在 0478 里它做不到。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    procedure/prəˈsiːdʒə/过程guò chéng
    decomposition/ˌdiːkɒmpəˈzɪʃn/分解fēn jiě
    definition/ˌdefɪˈnɪʃn/定义dìng yì
    function/ˈfʌŋkʃn/函数hán shù
    parameter/pəˈræmɪtə/参数cān shù
    passed by value/pæst baɪ ˈvæljuː/传值chuán zhí
  • 10 File handling · ⁨文件处理⁩
    10.1

    写入文件

    English

    A file 文件 keeps data after the program ends. 0478 uses four commands, and every one names the file it works on.

    Three file modes 文件模式:

    Mode What it does
    WRITE start a new file — anything already there is lost
    APPEND add to the end of what is there 追加
    READ read from the start
    • One WRITEFILE writes one line.
    • CLOSEFILE is not optional. An unclosed file can lose the data still waiting to be written, and that is a stock exam answer.

    Common mistakes

    • FOR WRITE when you meant FOR APPEND, which silently destroys the old contents.
    • Forgetting CLOSEFILE.
    • Opening a file that is already open.
    中文

    文件(file)在程序结束后仍保存数据。0478 用四条命令,每一条都点名它所操作的文件。

    OPENFILE <file identifier> FOR WRITE
    WRITEFILE <file identifier>, <data>
    CLOSEFILE <file identifier>
    
    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    CLOSEFILE "names.txt"
    OUTPUT "Saved"
    

    三种文件模式(file mode):

    模式 作用
    WRITE 新建文件——原有内容全部丢失
    APPEND 追加到已有内容的末尾
    READ 从头读取
    OPENFILE "log.txt" FOR WRITE
    WRITEFILE "log.txt", "first"
    CLOSEFILE "log.txt"
    OPENFILE "log.txt" FOR APPEND
    WRITEFILE "log.txt", "second"
    CLOSEFILE "log.txt"
    OUTPUT "Both lines saved"
    
    • 一条 WRITEFILE 写一行。
    • CLOSEFILE 不是可选的。未关闭的文件可能丢失仍在等待写出的数据,这是一个常考的答案。

    常见错误

    • 本想 FOR APPEND 却写了 FOR WRITE,悄无声息地毁掉旧内容。
    • 忘记 CLOSEFILE。
    • 打开一个已经打开的文件。
    10.2

    读取文件到末尾

    English

    READFILE takes one line into a variable. The variable must be declared first.

    Normally you do not know how many lines there are, so you read until the end of the file — which is what the EOF function reports.

    EOF("names.txt") is TRUE once every line has been read, so WHILE NOT EOF(...) means while there is still something to read.

    Counting while reading

    Common mistakes

    • A WHILE EOF(...) loop — that runs only when there is nothing left. You want NOT.
    • Reading past the end because the loop has no EOF guard.
    • Opening FOR READ a file that was never written.
    中文

    READFILE 把一行读入一个变量。该变量必须先声明。

    OPENFILE <file identifier> FOR READ
    READFILE <file identifier>, <variable>
    CLOSEFILE <file identifier>
    

    通常你并不知道有多少行,所以要一直读到文件末尾——这正是 EOF 函数所报告的。

    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    WRITEFILE "names.txt", "Ana"
    CLOSEFILE "names.txt"
    
    DECLARE Line : STRING
    OPENFILE "names.txt" FOR READ
    WHILE NOT EOF("names.txt") DO
        READFILE "names.txt", Line
        OUTPUT Line
    ENDWHILE
    CLOSEFILE "names.txt"
    

    EOF("names.txt") 在每一行都读完之后变为 TRUE,所以 WHILE NOT EOF(...) 的意思是还有东西可读时。

    边读边计数

    OPENFILE "marks.txt" FOR WRITE
    WRITEFILE "marks.txt", 40
    WRITEFILE "marks.txt", 65
    WRITEFILE "marks.txt", 88
    CLOSEFILE "marks.txt"
    
    DECLARE Mark, Count, Total : INTEGER
    Count ← 0
    Total ← 0
    OPENFILE "marks.txt" FOR READ
    WHILE NOT EOF("marks.txt") DO
        READFILE "marks.txt", Mark
        Count ← Count + 1
        Total ← Total + Mark
    ENDWHILE
    CLOSEFILE "marks.txt"
    OUTPUT Count, " marks, mean ", Total / Count
    

    常见错误

    • 写成 WHILE EOF(...)——那只在没有东西可读时才运行。你要的是 NOT。
    • 循环没有 EOF 守卫,读过了文件末尾。
    • 对一个从未写入过的文件 FOR READ。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    file/faɪl/文件wén jiàn
    file modes/faɪl məʊdz/文件模式wén jiàn mó shì
    to the end of what is there/tə ðɪ end ɒv wɒt ɪz ðeə/追加zhuī jiā
  • 11 A-Level 9618: what changes · ⁨A-Level 9618:有何不同⁩
    11.1

    排版与运算符

    English

    Cambridge publishes two pseudocode specifications, and they disagree. Everything in topics 1-10 is IGCSE 0478. A-Level 9618 changes the details below — and a student who studies both loses marks by writing one in the other's paper.

    IGCSE 0478 A-Level 9618
    THEN on its own line, indented 2 on the IF line
    constants CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD functions: DIV(10, 3) operators: 10 DIV 3
    joining strings commas in OUTPUT the & operator
    identifiers must start with a capital mixed case allowed 混合大小写
    NEXT must name its counter good practice
    ROUND, RANDOM() both published neither exists

    This is the 0478 form, and it runs here:

    The 9618 form of the same algorithm is written like this — note THEN on the IF line, = in the CONSTANT, and MOD between its two values:

    ⚠️ Which one is right depends only on which paper you are sitting. Neither is a mistake; each is a mistake in the other's exam. The playground on this page runs the 0478 rules, so a 9618 construct is refused with a message naming the syllabus it belongs to — which is a quick way to check your own habits.

    Common mistakes

    • Writing THEN on the IF line in an 0478 answer, because that is what a textbook or a website showed. It is the single commonest cross-syllabus slip.
    • 10 MOD 3 in 0478. There it is MOD(10, 3).
    • ROUND(3.14159, 2) in a 9618 answer. 9618 has no ROUND at all.
    中文

    剑桥公布了两份伪代码规范,而且它们互相不一致。主题 1-10 讲的全部是 IGCSE 0478。A-Level 9618 改动了下面这些细节——同时学两者的学生,常因把一种写进另一种的卷子而丢分。

    IGCSE 0478 A-Level 9618
    THEN 独占一行,缩进 2 写在 IF 那一行
    常量 CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD 函数:DIV(10, 3) 运算符:10 DIV 3
    连接字符串 OUTPUT 中用逗号 & 运算符
    标识符 必须以大写开头 允许混合大小写
    NEXT 必须写出计数器 属于良好习惯
    ROUND、RANDOM() 两者都有 都没有

    这是 0478 的写法,在本页可以运行:

    DECLARE Total : REAL
    CONSTANT Rate ← 0.5
    Total ← 10
    IF MOD(7, 2) = 1
      THEN
        OUTPUT "Odd, half rate ", Total * Rate
    ENDIF
    

    同一算法的 9618 写法是这样——注意 THEN 在 IF 那一行、CONSTANT 用 =、MOD 写在两个值之间:

    DECLARE Total : REAL
    CONSTANT Rate = 0.5
    Total ← 10
    IF 7 MOD 2 = 1 THEN
        OUTPUT "Odd, half rate " & STR(Total * Rate)
    ENDIF
    

    ⚠️ 哪一种正确,只取决于你考哪一张卷。 两者都不是错误,但各自在对方的考试中都是错误。本页的运行环境按 0478 的规则执行,所以 9618 的写法会被拒绝,并给出一条指明其所属考纲的提示——这是检查自己书写习惯的快捷办法。

    常见错误

    • 在 0478 答卷中把 THEN 写在 IF 那一行,因为某本教材或某个网站是那样写的。这是最常见的跨考纲错误。
    • 在 0478 中写 10 MOD 3。那里应写 MOD(10, 3)。
    • 在 9618 答卷中写 ROUND(3.14159, 2)。9618 根本没有 ROUND。
    11.2

    参数:BYVAL 与 BYREF

    English

    0478 passes every parameter by value 传值 (topic 9). 9618 lets you choose, and says so in the header.

    • BYVAL — the procedure gets a copy. Changing it changes nothing outside. This is the default when neither word is written.
    • BYREF — the procedure works on the caller's own variable 引用, so a change is visible after the call.

    This is 9618 only. It does not run here, and it is not accepted in an 0478 answer:

    The 0478 way to get a value back

    Use a FUNCTION and assign what it returns. This is the whole of the 0478 answer, and it runs:

    Common mistakes

    • Writing BYREF in an 0478 answer. The keyword is not in that syllabus.
    • Expecting a plain 9618 parameter to behave like BYREF. Without the word it is BYVAL.
    中文

    0478 的每个参数都按值传递(主题 9)。9618 让你选择,并在头部写明。

    • BYVAL——过程拿到一个副本。改动它,外面毫无变化。不写这两个词时,默认就是它。
    • BYREF——过程操作的是调用者自己的变量(引用),所以调用之后能看到改动。

    这只属于 9618。它在本页不能运行,在 0478 答卷中也不被接受:

    PROCEDURE Increase(BYREF Value : INTEGER)
        Value ← Value + 1
    ENDPROCEDURE
    
    DECLARE Count : INTEGER
    Count ← 5
    CALL Increase(Count)
    OUTPUT Count      // prints 6
    

    0478 取回值的办法

    用 FUNCTION,并把它返回的东西赋回去。这就是 0478 答案的全部,而且可以运行:

    FUNCTION Increased(Value : INTEGER) RETURNS INTEGER
        RETURN Value + 1
    ENDFUNCTION
    
    DECLARE Count : INTEGER
    Count ← 5
    Count ← Increased(Count)
    OUTPUT Count
    

    常见错误

    • 在 0478 答卷中写 BYREF。该关键字不在那份考纲里。
    • 以为 9618 中不加修饰的参数会像 BYREF 一样。不写那个词就是 BYVAL。
    11.3

    记录与其他类型

    English

    9618 has data structures 数据结构 that 0478 does not. You will meet them only at A-Level, and none of them runs under the 0478 rules of this page.

    A record 记录 groups fields of different types under one name (9618 section 4):

    An enumerated type 枚举类型 lists the only values a variable may take:

    9618 also adds a DATE data type, random-access files (OPENFILE … FOR RANDOM), pointers, and classes with CLASS … ENDCLASS for its object-oriented paper.

    ⚠️ 0478 has five data types and arrays, and nothing else (topic 2). A 0478 answer that declares a record is answering a different syllabus.

    Common mistakes

    • Using a record in an 0478 answer. Use parallel arrays instead — one array per field, sharing an index.
    • Thinking TYPE means the same as DECLARE. TYPE defines a new type; DECLARE creates a variable of an existing one.
    中文

    9618 拥有 0478 所没有的数据结构(data structure)。你只会在 A-Level 遇到它们,而且它们都不能在本页的 0478 规则下运行。

    记录(record)把不同类型的字段归到一个名字下(9618 第 4 节):

    TYPE Student
        DECLARE Name : STRING
        DECLARE Mark : INTEGER
    ENDTYPE
    
    DECLARE Candidate : Student
    Candidate.Name ← "Mei"
    Candidate.Mark ← 91
    OUTPUT Candidate.Name, " scored ", Candidate.Mark
    

    枚举类型(enumerated type)列出一个变量只能取的那些值:

    TYPE Vehicle = (Car, Bus, Taxi)
    DECLARE MyRide : Vehicle
    MyRide ← Taxi
    

    9618 还增加了 DATE 数据类型、随机存取文件(OPENFILE … FOR RANDOM)、指针,以及面向对象卷所用的 CLASS … ENDCLASS。

    ⚠️ 0478 只有五种数据类型和数组(主题 2),别无其他。在 0478 答卷中声明一个记录,等于在回答另一份考纲。

    常见错误

    • 在 0478 答卷中使用记录。请改用平行数组——每个字段一个数组,共用一个下标。
    • 以为 TYPE 和 DECLARE 是一回事。TYPE 定义一个新类型;DECLARE 创建一个已有类型的变量。
    Vocabulary · ⁨词汇⁩
    English中文Pinyin · ⁨拼音⁩
    mixed case/mɪkst keɪs/混合大小写hùn hé dà xiǎo xiě
    by value/baɪ ˈvæljuː/传值chuán zhí
    own variable/əʊn ˈveərɪəbl/引用yǐn yòng
    data structures/ˈdeɪtə ˈstrʌktʃəz/数据结构shù jù jié gòu
    record/ˈrekɔːd/记录jì lù
    enumerated type/ɪˈnjuːməreɪtɪd taɪp/枚举类型méi jǔ lèi xíng

Log in or create account · ⁨登录或创建账户⁩

IGCSE, A-Level · ⁨IGCSE、A-Level⁩ & AP · ⁨与 AP⁩