Operators in Programming | 编程中的运算符

📚 Operators in Programming | 编程中的运算符

Operators are fundamental building blocks in any programming language. They enable us to perform calculations, compare values, combine conditions, and manipulate data at a low level. In A-Level Computer Science, understanding operators is crucial for writing efficient algorithms, designing control flow, and predicting the outcome of expressions. This article explores the main categories of operators, their symbols, behaviour, precedence, and typical usage across modern high-level languages.

运算符是所有编程语言的基本构建块。它们使我们能够进行计算、比较值、组合条件以及进行底层数据操作。在 A-Level 计算机科学中,理解运算符对于编写高效算法、设计控制流以及预测表达式结果至关重要。本文探讨运算符的主要类别、符号、行为、优先级以及在现代高级语言中的典型用法。


1. Introduction to Operators | 运算符简介

An operator is a symbol or keyword that tells the compiler or interpreter to perform a specific mathematical, logical, or relational operation. Operators act on operands – the values or variables that sit on either side of the operator. For example, in the expression a + b, + is the operator, while a and b are operands. Depending on how many operands they take, operators can be unary (one operand), binary (two operands), or ternary (three operands).

运算符是一种符号或关键字,它告诉编译器或解释器执行特定的数学、逻辑或关系运算。运算符作用于操作数——即位于运算符两侧的值或变量。例如,在表达式 a + b 中,+ 是运算符,ab 是操作数。根据它们所接受的操作数数量,运算符可以是一元运算符(一个操作数)、二元运算符(两个操作数)或三元运算符(三个操作数)。

Operators are classified into several standard groups: arithmetic, comparison, logical, bitwise, assignment, and string. Each group has its own set of symbols and rules. In Edexcel specifications, candidates are expected to know these operators and apply them correctly in pseudocode and programming tasks, especially when constructing conditions for IF statements, loops, and Boolean algebra simplifications.

运算符分为几个标准组别:算术、比较、逻辑、位运算、赋值和字符串。每个组别都有自己的一套符号和规则。在 Edexcel 课程大纲中,考生应了解这些运算符,并能在伪代码和编程任务中正确应用它们,特别是在构建 IF 语句、循环和布尔代数简化的条件时。


2. Arithmetic Operators | 算术运算符

Arithmetic operators handle basic mathematical operations. The most common include addition (+), subtraction (-), multiplication (*), and division (/). In integer-based contexts, certain languages provide integer division (DIV) and modulus (MOD) operators. For instance, in Python, 7 // 2 gives 3, and 7 % 2 gives 1. The modulus operator returns the remainder of a division and is extensively used in algorithms for parity checks and cyclic constructs.

算术运算符处理基本的数学运算。最常见的包括加法 (+)、减法 (-)、乘法 (*) 和除法 (/)。在基于整数的上下文中,某些语言提供整数除法 (DIV) 和模运算 (MOD) 运算符。例如,在 Python 中,7 // 2 得到 3,7 % 2 得到 1。模运算符返回除法的余数,广泛用于奇偶校验和循环结构的算法中。

Unary plus and minus are also arithmetic operators. -x negates the value of x. Some languages include exponentiation, such as ** in Python or ^ in some dialects of BASIC, but note that in many C-family languages ^ is the bitwise XOR operator. Understanding these distinctions prevents common mistakes when moving between languages.

一元加法和减法也属于算术运算符。-x 对 x 取反。某些语言包含指数运算,如 Python 中的 ** 或某些 BASIC 方言中的 ^,但请注意,在许多 C 系语言中,^ 是按位异或运算符。理解这些区别可以避免在不同语言之间切换时出现常见错误。

Operator Name Example
+ Addition x + y
Subtraction x – y
* Multiplication x * y
/ Division x / y
DIV or // Integer division x DIV y
MOD or % Modulus x MOD y

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

Comparison operators evaluate the relationship between two operands and return a Boolean value: TRUE or FALSE. The standard set includes equal to (= or ==), not equal to (≠ or !=), greater than (>), less than (<), greater than or equal to (≥ or >=), and less than or equal to (≤ or <=). In many exam pseudocode notations, the equality check uses a single equals sign '=', while assignment might use '←'; however, in actual programming languages like Python, '==' denotes equality and '=' is assignment.

比较运算符评估两个操作数之间的关系,并返回一个布尔值:TRUE 或 FALSE。标准集合包括等于(= 或 ==)、不等于(≠ 或 !=)、大于(>)、小于(<)、大于或等于(≥ 或 >=)以及小于或等于(≤ 或 <=)。在许多考试伪代码符号中,相等性检查使用单等号 '=',而赋值可能使用 '←';然而,在实际编程语言如 Python 中,'==' 表示相等,'=' 是赋值。

These operators are the backbone of control flow statements. For example, an IF statement might test IF score >= 75 THEN to decide on a result. When chaining comparisons, it is vital to respect data types; comparing strings uses lexicographical order in most languages, and comparing floating‑point numbers for exact equality can lead to logic errors due to precision limitations.

这些运算符是控制流语句的骨干。例如,一个 IF 语句可能会测试 IF score >= 75 THEN 来决定结果。当链接比较时,遵守数据类型至关重要;大多数语言中字符串比较使用字典顺序,而由于精度限制,对浮点数进行精确相等性检查可能导致逻辑错误。

Operator Meaning
== or = equal to
!= or ≠ not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

In some languages, strict comparison operators like ‘===’ exist (JavaScript) to check both value and type without type coercion, but typical A-Level pseudocode sticks to the simpler relational set.

在某些语言中,存在如 ‘===’ 的严格比较运算符(JavaScript),用于在不进行类型转换的情况下检查值和类型,但典型的 A-Level 伪代码坚持使用更简单的关系运算集。


4. Logical Operators | 逻辑运算符

Logical operators work on Boolean values and are essential for building complex conditions. The three fundamental logical operators are AND, OR, and NOT. In many programming languages, AND is represented by ‘&&’ or the keyword ‘and’, OR by ‘||’ or ‘or’, and NOT by ‘!’ or ‘not’. These correspond directly to the logical gates AND, OR, and NOT in Boolean algebra.

逻辑运算符处理布尔值,是构建复杂条件的关键。三种基本逻辑运算符是 AND、OR 和 NOT。在许多编程语言中,AND 用 ‘&&’ 或关键字 ‘and’ 表示,OR 用 ‘||’ 或 ‘or’ 表示,NOT 用 ‘!’ 或 ‘not’ 表示。它们直接对应于布尔代数中的与门、或门和非门。

Truth tables define the output for all input combinations. For example, a AND b is TRUE only if both a and b are TRUE. Short‑circuit evaluation is an important feature: if the left operand of an AND is FALSE, the entire expression is FALSE without evaluating the right side. Similarly, an OR short-circuits when the left side is TRUE. This can be used to guard against runtime errors, e.g., IF (x ≠ 0) AND (y/x > 5) THEN avoids division by zero.

真值表定义了所有输入组合的输出。例如,a AND b 仅当 a 和 b 都为 TRUE 时才为 TRUE。短路评估是一个重要特性:如果 AND 的左操作数为 FALSE,则整个表达式为 FALSE,而无需评估右侧。同样,OR 在左侧为 TRUE 时短路。这可以用来防止运行时错误,例如,IF (x ≠ 0) AND (y/x > 5) THEN 避免了除数为零。

NOT(A AND B) = (NOT A) OR (NOT B)

This is one of De Morgan’s laws, frequently used to simplify conditional statements in code.

这是德摩根定律之一,常用于简化代码中的条件语句。


5. Bitwise Operators | 位运算符

Bitwise operators perform operations on the binary representations of integers. They treat each bit independently. The common bitwise operators are AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). These are extremely useful in low‑level programming, hardware manipulation, cryptography, and performance optimisations.

位运算符对整数的二进制表示进行运算。它们独立处理每一位。常见的位运算符包括 AND (&)、OR (|)、XOR (^)、NOT (~)、左移 (<<) 和右移 (>>)。这些在底层编程、硬件操作、密码学和性能优化中极为有用。

For example, 5 & 3 (binary 101 & 011) yields 1 (001). The XOR operator returns 1 where bits differ; 5 ^ 3 yields 6 (110). Left shift (n << k) effectively multiplies n by 2ⁱ, while right shift (n >> k) performs integer division by 2ⁱ. These shift operations are often faster than multiplication or division by powers of two.

例如,5 & 3(二进制 101 & 011)得到 1 (001)。XOR 运算符在位不同时返回 1;5 ^ 3 得到 6 (110)。左移 (n << k) 相当于将 n 乘以 2 的 k 次方,而右移 (n >> k) 则是整数除以 2 的 k 次方。这些移位操作通常比乘除 2 的幂次更快。

Bitwise NOT (~) inverts each bit; however, the result depends on whether the representation is two’s complement. In many languages, ~x equals -x – 1 because of two’s complement arithmetic. A-Level students should be able to trace simple bitwise operations on 8‑bit values as part of their understanding of data representation.

位非 (~) 反转每一位;然而,其结果取决于是否为补码表示。在许多语言中,~x 等于 -x – 1,这是因为采用了二进制补码算术。A-Level 学生应能够对 8 位值进行简单的位运算跟踪,作为他们对数据表示理解的一部分。


6. Assignment Operators | 赋值运算符

Assignment operators are used to store a value in a variable. The basic assignment operator is ‘=’ in many languages (or ‘←’ in pseudocode). Compound assignment operators combine an arithmetic or bitwise operation with assignment. Examples include +=, -=, *=, /=, and %=. The statement x += 5 is a shorthand for x = x + 5. This not only reduces typing but can sometimes lead to more efficient code, as the variable’s address is evaluated only once.

赋值运算符用于将值存储到变量中。基本赋值运算符在许多语言中是 ‘=’(或伪代码中的 ‘←’)。复合赋值运算符将算术或位运算与赋值结合起来。示例包括 +=-=*=/=%=。语句 x += 5x = x + 5 的简写。这不仅减少了输入量,有时还能产生更高效的代码,因为变量的地址只被计算一次。

Increment (++) and decrement () operators are unary assignment shortcuts found in C‑style languages. They can be used in prefix or postfix form: ++x increments x and returns the new value, whereas x++ returns the original value before incrementing. These nuances can affect loop counters and expressions where the returned value matters.

自增(++)和自减()运算符是 C 风格语言中的一元赋值快捷方式。它们可以以前缀或后缀形式使用:++x 将 x 递增并返回新值,而 x++ 返回递增前的原始值。这些细微差别会影响循环计数器和返回值在意的表达式。

In pseudocode used by Edexcel, simple assignment is generally expressed as SET variable TO value or using the arrow notation. Compound assignments are less common in pseudocode but should be understood when translating algorithms into real code.

在 Edexcel 使用的伪代码中,简单赋值通常表示为 SET 变量 TO 值 或使用箭头符号。复合赋值在伪代码中不太常见,但在将算法转换为实际代码时应理解。


7. String Concatenation Operators | 字符串连接运算符

String operators are used to manipulate text data. The most common string operator is concatenation, often symbolised by ‘+’ in many languages (e.g., Python, Java, JavaScript). For instance, ‘Hello ‘ + ‘World’ results in ‘Hello World’. In other languages like PHP, the dot ‘.’ operator serves the same purpose, and in SQL, ‘||’ or the CONCAT function is used.

字符串运算符用于操作文本数据。最常见的字符串运算符是连接,通常在许多语言中用 ‘+’ 表示(如 Python、Java、JavaScript)。例如,‘Hello ‘ + ‘World’ 结果是 ‘Hello World’。在 PHP 等其他语言中,点号 ‘.’ 运算符具有相同作用,在 SQL 中则使用 ‘||’ 或 CONCAT 函数。

Concatenation can involve implicit type conversion when one operand is not a string. For example, ‘Score: ‘ + 95 might automatically convert the number 95 to a string to produce ‘Score: 95’. However, relying on implicit conversion can cause bugs. Many modern languages recommend using explicit conversion functions such as str() or toString() to avoid ambiguity.

当操作数之一不是字符串时,连接可能涉及隐式类型转换。例如,‘Score: ‘ + 95 可能会自动将数字 95 转换为字符串以生成 ‘Score: 95’。然而,依赖隐式转换可能导致错误。许多现代语言建议使用显式转换函数,如 str()toString() 以避免歧义。

In some languages, strings support other operators like repetition. In Python, ‘Hi’ * 3 produces ‘HiHiHi’. Understanding these string-specific operators is important for data formatting and output generation tasks commonly found in A-Level programming projects.

在某些语言中,字符串还支持其他运算符,如重复。在 Python 中,‘Hi’ * 3 生成 ‘HiHiHi’。理解这些特定于字符串的运算符对于 A-Level 编程项目中常见的数据格式化和输出生成任务非常重要。


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

When multiple operators appear in an expression, precedence rules determine which operation is performed first. For example, multiplication has higher precedence than addition, so 3 + 5 * 2 evaluates to 13, not 16. Parentheses can override precedence, and using them generously is a good practice for clarity.

当表达式中出现多个运算符时,优先级规则决定哪个运算先执行。例如,乘法优先级高于加法,因此 3 + 5 * 2 计算结果为 13,而不是 16。括号可以覆盖优先级,大量使用括号是确保清晰性的良好实践。

Associativity defines the direction of evaluation for operators of the same precedence. Most arithmetic operators are left‑associative, meaning they group from left to right: a – b – c is equivalent to (a – b) – c. The assignment operator ‘=’ is right‑associative, allowing chained assignments like x = y = 0, which sets both variables to zero. Unary and conditional (ternary) operators are also right‑associative in many languages.

结合性定义了相同优先级运算符的求值方向。大多数算术运算符是左结合的,意味着它们从左向右分组:a – b – c 等价于 (a – b) – c。赋值运算符 ‘=’ 是右结合的,允许链式赋值如 x = y = 0,将两个变量都设为零。一元和条件(三元)运算符在许多语言中也是右结合的。

A typical simplified precedence from highest to lowest might be: parentheses, unary operators ! and -, then */ and DIV/MOD, then + -, then relational < > <= >=, then equality == !=, then logical AND, then logical OR, and finally assignment. The exact order can vary slightly between languages, so exam questions often provide a precedence table if needed.

从高到低的一个典型简化优先级可能是:括号、一元运算符 ! 和 -、然后是 */ 和 DIV/MOD、接着是 + -、再是关系运算符 < > <= >=、然后是相等性 == !=、接着是逻辑 AND、然后是逻辑 OR、最后是赋值。具体顺序可能因语言而略有不同,因此考试题目在必要时通常会提供优先级表。


9. Overloading and Special Cases | 重载与特殊情况

Operator overloading allows the same operator symbol to behave differently based on operand types. For example, in Python and C++, ‘+’ can add numbers or concatenate strings. In custom classes, programmers can define what ‘+’ means for user‑defined types. While this provides expressive power, it can lead to confusion if not used carefully. A-Level exams generally focus on built‑in behaviour, but awareness of overloading helps in understanding language design.

运算符重载允许同一个运算符符号根据操作数类型表现出不同的行为。例如,在 Python 和 C++ 中,’+’ 可以加数字或连接字符串。在自定义类中,程序员可以定义 ‘+’ 对用户定义类型的含义。虽然这提供了表达能力,但若不谨慎使用可能导致混淆。A-Level 考试通常关注内置行为,但了解重载有助于理解语言设计。

The ternary operator is a special three‑operand operator: condition ? expr1 : expr2 in C‑style languages, or expr1 if condition else expr2 in Python. It provides a compact conditional expression. For instance, result = (score >= 50) ? ‘Pass’ : ‘Fail’. This can replace simple IF‑ELSE statements, but overuse may harm readability.

三元运算符是一种特殊的三操作数运算符:C 风格语言中的 condition ? expr1 : expr2,或 Python 中的 expr1 if condition else expr2。它提供了紧凑的条件表达式。例如,result = (score >= 50) ? ‘Pass’ : ‘Fail’。这可以取代简单的 IF‑ELSE 语句,但过度使用可能损害可读性。

Other special cases include the ‘space ship’ operator <=> in PHP and Ruby for combined comparison, and the power operator **. In Edexcel pseudocode, such specialised operators are rare, but they appear in practical programming tasks.

其他特殊情况包括 PHP 和 Ruby 中用于组合比较的 ‘太空船’ 运算符 <=>,以及幂运算符 **。在 Edexcel 伪代码中,这种专门的运算符很少见,但它们出现在实际编程任务中。


10. Summary and Key Points | 总结与要点

Operators are a core concept in computer science, essential for performing calculations, making decisions, and manipulating data. Mastery of arithmetic, comparison, logical, bitwise, and string operators, along with their precedence and associativity, equips students to write correct and efficient code. Key takeaways: use parentheses to clarify intent; understand short‑circuit evaluation to write safer conditions; be cautious with implicit type conversions; know the difference between equality and assignment; and practice tracing bitwise operations for strong fundamentals.

运算符是计算机科学的核心概念,对于执行计算、做出决策和操作数据至关重要。掌握算术、比较、逻辑、位运算和字符串运算符,以及它们的优先级与结合性,使学生能够编写正确高效的代码。要点:使用括号阐明意图;理解短路评估以编写更安全的条件;警惕隐式类型转换;了解相等与赋值的区别;并练习跟踪位运算以打下坚实基础。

For Edexcel A-Level programming, always check the pseudocode guide. Typical notation uses standard operators but with a few specific conventions. Regular practice with past papers and practical coding tasks will solidify your understanding and help you avoid common pitfalls.

对于 Edexcel A-Level 编程,请始终查阅伪代码指南。典型的符号使用标准运算符,但有一些特定的惯例。定期练习历年真题和实际编码任务将巩固你的理解,并帮助你避免常见陷阱。

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