Combined Operations and Expressions in Programming | 编程中的组合操作与表达式

📚 Combined Operations and Expressions in Programming | 编程中的组合操作与表达式

In A-Level Computer Science, a firm grasp of operators and how they combine to form expressions is fundamental. This article explores arithmetic, relational, and logical operators, operator precedence, type conversion, and the evaluation of combined expressions using pseudocode and Python examples aligned with the Edexcel specification.

在A-Level计算机科学中,牢固掌握运算符及其组合形成表达式的方式是基础。本文探讨算术、关系和逻辑运算符、运算符优先级、类型转换以及组合表达式的求值,使用符合Edexcel规范的伪代码和Python示例。

1. Arithmetic Operators | 算术运算符

Arithmetic operators perform basic mathematical calculations on numeric operands. They include addition (+), subtraction (-), multiplication (*), division (/), integer division (DIV or //), and modulus (MOD or %). These operators are binary, requiring two operands, except for unary minus (e.g., -x).

算术运算符对数值操作数执行基本数学计算。它们包括加法(+)、减法(-)、乘法(*)、除法(/)、整数除法(DIV 或 //)和取模(MOD 或 %)。这些运算符是二元的,需要两个操作数,一元负号(如 -x)除外。

  • Division / always yields a real (float) result, even if both operands are integers.
  • 除法 / 总是产生实数(浮点)结果,即使两个操作数都是整数。
  • Integer division DIV (or // in Python) truncates towards negative infinity, giving the quotient without the remainder.
  • 整数除法 DIV(或 Python 中的 //)向负无穷方向截断,给出不带余数的商。
  • Modulus MOD (or %) returns the remainder of integer division, e.g., 17 MOD 5 = 2.
  • 取模 MOD(或 %)返回整数除法的余数,例如 17 MOD 5 = 2。

Use parentheses to override default precedence and clarify intent. For example, (a + b) * c is evaluated differently from a + b * c.

使用括号可覆盖默认优先级并明确意图。例如,(a + b) * c 与 a + b * c 的求值方式不同。


2. Relational (Comparison) Operators | 关系(比较)运算符

Relational operators compare two values and produce a Boolean result (TRUE or FALSE). Standard operators are: = (equals), <> or != (not equals), < (less than), > (greater than), <= (less than or equal), >= (greater than or equal).

关系运算符比较两个值并产生布尔结果(TRUE 或 FALSE)。标准运算符有:= (等于), <> 或 != (不等于), < (小于), > (大于), <= (小于等于), >= (大于等于)。

In pseudocode, assignment uses ← while comparison uses =; do not confuse them. For strings, comparisons are lexicographical based on character codes.

在伪代码中,赋值使用 ← 而比较使用 =;不要混淆。对于字符串,比较基于字符编码按字典序进行。

Be careful when comparing floating‑point values directly due to rounding errors. Instead check if the absolute difference is less than a small epsilon.

由于舍入误差,直接比较浮点值时要小心。相反,应检查绝对差是否小于一个极小的 epsilon。


3. Logical (Boolean) Operators | 逻辑(布尔)运算符

Logical operators combine Boolean expressions. The primary operators are AND, OR, and NOT. AND returns TRUE only if both operands are TRUE. OR returns TRUE if at least one operand is TRUE. NOT negates a Boolean value.

逻辑运算符组合布尔表达式。主要运算符有 AND、OR 和 NOT。AND 仅当两个操作数均为 TRUE 时返回 TRUE。OR 至少一个操作数为 TRUE 时返回 TRUE。NOT 对布尔值取反。

Truth tables are essential for evaluating logical expressions:

真值表对于求值逻辑表达式至关重要:

A B A AND B A OR B NOT A
FALSE FALSE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE TRUE
TRUE FALSE FALSE TRUE FALSE
TRUE TRUE TRUE TRUE FALSE

Short‑circuit evaluation stops as soon as the outcome is known: for AND, if the first operand is FALSE, the second is not evaluated; for OR, if the first is TRUE, the second is skipped.

短路求值在结果已知时立即停止:对于 AND,若第一个操作数为 FALSE 则不再计算第二个;对于 OR,若第一个为 TRUE 则跳过第二个。


4. Operator Precedence and Associativity | 运算符优先级与结合性

When multiple operators appear in an expression, precedence determines the order of evaluation. Highest to lowest: parentheses, unary minus/ NOT, multiplicative (* , / , DIV, MOD), additive (+ , -), relational (< , > , <= , >=), equality (= , <> ), logical AND, logical OR.

当一个表达式中有多个运算符时,优先级决定求值顺序。从高到低:括号、一元负号/NOT、乘除(*、/、DIV、MOD)、加减(+、-)、关系(<、>、<=、>=)、相等(=、<>)、逻辑 AND、逻辑 OR。

Associativity rules apply for operators of the same precedence. Most operators are left‑associative (evaluated left‑to‑right), except unary operators and assignment which are right‑associative.

结合性规则适用于优先级相同的运算符。大多数运算符是左结合的(从左到右求值),但一元运算符和赋值是右结合的。

For example: a + b * c is evaluated as a + (b * c). In a / b * c, the left‑to‑right rule gives (a / b) * c.

例如:a + b * c 作为 a + (b * c) 求值。在 a / b * c 中,左结合规则给出 (a / b) * c。


5. Type Conversion in Expressions | 表达式中的类型转换

Implicit type conversion (coercion) occurs when operators are applied to operands of different types. For instance, adding an integer and a real number promotes the integer to real before addition. Division always yields a real result.

当运算符应用于不同类型的操作数时会发生隐式类型转换(强制)。例如,整数与实数相加,整数先提升为实数再进行加法。除法始终产生实数结果。

Explicit type conversion functions like INT(), REAL(), STRING() or in Python int(), float(), str() allow the programmer to control conversion. Use them to avoid unintended truncation or string concatenation.

显式类型转换函数如 INT()、REAL()、STRING() 或 Python 中的 int()、float()、str() 允许程序员控制转换。使用它们可避免意外的截断或字符串连接。

Be mindful of the “+” operator: it adds numbers but concatenates strings. If one operand is a string, the other is coerced to a string in many languages, leading to bugs.

注意“+”运算符:它对数字执行加法,但对字符串执行连接。在许多语言中,若一个操作数为字符串,另一个会被强转为字符串,从而引发错误。


6. Evaluating Combined Expressions Step‑by‑Step | 逐步求值组合表达式

To evaluate a complex expression such as (x + y * 2 > 10) AND NOT (z < 5), follow precedence:

要计算复杂表达式,如 (x + y * 2 > 10) AND NOT (z < 5),请遵循优先级:

  • 1. Evaluate y * 2 (multiplication first).
  • 1. 计算 y * 2(乘法优先)。
  • 2. Evaluate x + (result) inside parentheses.
  • 2. 计算括号内的 x + (结果)。
  • 3. Compare that sum > 10 to get a Boolean.
  • 3. 比较该总和 > 10 以获得布尔值。
  • 4. Evaluate z < 5 to get a Boolean.
  • 4. 计算 z < 5 以获得布尔值。
  • 5. Apply NOT to the result of step 4.
  • 5. 对步骤 4 的结果应用 NOT。
  • 6. Combine the two Booleans with AND.
  • 6. 用 AND 组合这两个布尔值。

Writing out evaluation trees or truth tables helps avoid mistakes. Always use parentheses to make the intended order explicit.

写出求值树或真值表有助于避免错误。始终使用括号来明确预期顺序。


7. Logical Expressions in Selection and Iteration | 选择与迭代中的逻辑表达式

Combined expressions are critical in IF statements, CASE/SWITCH, and loop conditions. For instance:

组合表达式在 IF 语句、CASE/SWITCH 和循环条件中至关重要。例如:

IF (age >= 18) AND (hasLicense = TRUE) THEN …

This checks two conditions simultaneously, reducing nested IFs.

它同时检查两个条件,减少了嵌套的 IF。

In a WHILE loop, complex continuation conditions like (NOT found) AND (index < max) must be carefully ordered to avoid errors from short‑circuit evaluation or index out‑of‑bounds.

在 WHILE 循环中,复杂的继续条件如 (NOT found) AND (index < max) 必须仔细排序,以避免短路求值或索引越界错误。


8. Writing Robust Boolean Expressions | 编写健壮的布尔表达式

De Morgan’s laws help simplify and negate logical expressions:

德摩根定律有助于简化和否定逻辑表达式:

NOT (A AND B)   ⇌   (NOT A) OR (NOT B)

NOT (A OR B)   ⇌   (NOT A) AND (NOT B)

These are invaluable when forming loop exit conditions. For example, looping while NOT (x = 0) AND NOT (y = 0) is equivalent to NOT (x = 0 OR y = 0).

它们在形成循环退出条件时非常宝贵。例如,当 NOT (x = 0) AND NOT (y = 0) 时循环,等价于 NOT (x = 0 OR y = 0)。

Use parentheses to group sub‑expressions logically and avoid reliance on default precedence, making code more readable and maintainable.

使用括号对子表达式进行逻辑分组,避免依赖默认优先级,使代码更具可读性和可维护性。


9. Common Mistakes with Combined Operations | 组合操作的常见错误

1. Confusing = for assignment and comparison. In pseudocode, use ← for assignment; in Python, = is assignment, == is comparison.

1. 混淆赋值 = 与比较。伪代码中使用 ← 赋值;Python 中 = 是赋值,== 是比较。

2. Dividing two integers expecting a real result: use explicit float conversion or write 5.0 / 2.

2. 两个整数相除期望得到实数结果:使用显式浮点转换或写成 5.0 / 2。

3. Ignoring integer division and modulus behavior with negative numbers; e.g., -7 // 3 = -3 in Python (floor division). Always test edge cases.

3. 忽略负数在整数除法和取模中的行为;例如 Python 中 -7 // 3 = -3(向下取整)。始终测试边界情况。

4. Using logical operators on non‑Boolean values which may be coerced unexpectedly.

4. 在非布尔值上使用逻辑运算符,可能会被意外强制转换。


10. Practical Exercises for Exam Success | 应试实战练习

Practice evaluating expressions with given variable values. For example, given a=5, b=2, c=3, what is the value of a + b * c – a / b? Show the step‑by‑step evaluation in pseudocode and a trace table.

练习用给定的变量值求值表达式。例如,给定 a=5, b=2, c=3,a + b * c – a / b 的值是多少?在伪代码和跟踪表中展示逐步求值过程。

Build truth tables for compound logical expressions like (p AND q) OR (NOT p AND r). These appear frequently in multiple‑choice and extended‑response questions.

为复合逻辑表达式构建真值表,如 (p AND q) OR (NOT p AND r)。这些在多选和扩展作答题目中频繁出现。

Write pseudocode solutions that use combined conditions in IF‑THEN‑ELSE and WHILE loops, ensuring each Boolean expression is correct and well‑parenthesized.

编写在 IF‑THEN‑ELSE 和 WHILE 循环中使用组合条件的伪代码解决方案,确保每个布尔表达式正确且括号使用得当。

Published by TutorHao | Programming 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