变量#

介绍#

变量存储数据,并允许您在整个程序中重用和操作数据。C++ 是一种静态类型语言,这意味着您必须在创建变量时明确声明其类型。声明后,类型无法更改。例如:

int angle = 90;           // angle is an integer
char dist[] = "Distance"; // dist is an array of characters
double steps = 2.5;       // steps is a double

C++ 也是强类型的,这意味着如果不显式转换,就无法对不兼容的类型执行操作。例如:

int blocks = 2;              // blocks is an integer
char rings[] = "4";          // rings is a string
int result = blocks + rings; // Creates a compilation error

此 API 解释了 C++ 中常见的变量类型。虽然并非详尽无遗,但它涵盖了您在实际工作中最可能使用的类型。

  • 局部变量 – 在函数内部声明并仅在该范围内使用;最适合临时或独立的值。

  • 全局变量 – 在任何函数之外声明并在整个项目中使用;适合在函数之间共享数据。

  • 整数 – 用于计数、距离或任何不带小数的整数。

  • Double – 用于需要精确度的数学计算的高精度十进制数。

  • 浮点数 – 标准精度的十进制数,可用于测量或计算。

  • C 风格字符串 – 文本值,用于消息、标签或显示可读输出。

  • Boolean (bool)true or false values for logic and decision-making.

  • 数组 – 相同类型元素的固定大小集合。

  • 2D 数组 – 数组的数组;非常适合表示行、网格或表格状数据。

声明和分配变量#

To create a variable in C++, you must declare its type followed by the variable name, then optionally assign a value using the = operator:

int distance = 100;

命名变量时,必须遵守以下规则:

  • 名称不能包含特殊字符(例如感叹号)。

  • 名称不能以数字开头。

  • 名称中不能使用空格。

  • 该名称不能是 VEXcode 中的保留字(例如 Drivetrain)。

  • Variable names are case-sensitive (e.g., Distance and distance are different variables).

Local Variables#

局部变量是在函数或代码块内部定义的。它们只能在该函数或代码块的范围内访问,在其外部不可见。

void show_local() {
  // This variable only exists inside this function
  int angle = 90;
  Brain.Screen.print("%d", angle);
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Begin project code
  show_local();
}

局部变量通常用于存储仅与特定函数或程序部分相关的临时值。

Global Variables#

全局变量 定义在任何函数或块的外部。它们可以在程序的任何地方访问和读取,包括函数内部。

注意全局变量可以在程序的任何位置访问,这使得它们可以方便地跨函数共享数据。然而,过度依赖全局变量可能会导致意想不到的副作用,因为在程序的某个部分对变量的更改可能会对其他部分产生不可预测的影响。因此,在可能的情况下,通常优先使用局部变量,因为它们将变量的作用域限制在其定义的特定函数内。这可以降低冲突的可能性并使调试更容易。

// The variable is defined outside a function
int angle = 90;

void show_global() {
  // You can access 'angle' inside a function
  Brain.Screen.print("%d", angle);
  Brain.Screen.newLine();
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Begin project code
  show_global();
  Brain.Screen.print("%d", angle);
}

In C++, global variables can be directly accessed and modified from within functions without any special keywords. However, if you have a local variable with the same name, you can use the scope resolution operator :: to access the global variable.

// Define the global variable
int count = 0;

void increase_count() {
  // Global variables can be accessed directly
  count = count + 1;
  Brain.Screen.print("Count: %d", count);
  Brain.Screen.newLine();
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Begin project code
  increase_count();
  increase_count();
}

数据类型#

C++ 变量可以存储各种类型的数据,每种类型都适用于不同的用例。以下是最常用的类型:

Integer#

整数int)是一个整数。

int distance = 100;

// Move the robot forward for the variable value in mm
Drivetrain.driveFor(forward, distance, mm);

// Add to the variable and move forward the new value, 
// for 200mm total
wait(1, seconds);
distance = distance + 100;
Drivetrain.driveFor(forward, distance, mm);

Double#

double 是具有高精度(通常为 64 位)的小数。

// Store a value with decimal points
double raw_value = 0.88;

// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);

Float#

浮点数 是具有标准精度(通常为 32 位)的小数。

// Store a value with decimal points
float raw_value = 0.88;

// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);

String#

C 风格的字符串char variable_name[])是一个字符数组,通常用于文本。

// Set the variable to a string then print the string
char message[] = "Ready!";
Brain.Screen.print(message);

Boolean#

A Boolean (bool) represents true or false values.

// Set the state of the variable
bool delivered = false;

// Print different messages depending on the Boolean.
if (delivered) {
    Brain.Screen.print("Package delivered!");
} else {
    Brain.Screen.print("Delivering...");
}

布尔值可以在项目的任何时候改变。

// Print the value of the delivered variable
bool delivered = false;
// Print different messages depending on the Boolean.
if (delivered) {
    Brain.Screen.print("Package delivered!");
} else {
    Brain.Screen.print("Delivering...");
}
wait(2, seconds);

// Clear the screen and print the value of the variable again
Brain.Screen.clearScreen();
Brain.Screen.setCursor(1,1);
delivered = true;
// Print different messages depending on the Boolean.
if (delivered) {
    Brain.Screen.print("Package delivered!");
} else {
    Brain.Screen.print("Delivering...");
}

Arrays#

数组 是相同类型元素的固定大小集合。最好在创建数组时就确定其长度并进行声明。

// Declare an array of 5 integers
int distances[5] = {100, 200, 150, 300, 250};

// Drive and turn 4 times to move the distance of the first four distance of the array
for (int i = 0; i < 4; i++) {
    Drivetrain.driveFor(forward, distances[i], mm);
    Drivetrain.turnFor(right, 90, degrees);
}

2D Arrays#

二维数组通常用于表示网格、表格或矩阵。每一行代表一组特定的数据。

// Assign the values in the matrix 2D array
int matrix[3][3] = {
  { 0, 1, 2 },
  { 3, 4, 5 },
  { 6, 7, 8 }
};

// Loop through each row
for (int i = 0; i < 3; i++) {
    // Loop through each column in the row
    for (int j = 0; j < 3; j++) {
        Brain.Screen.print("%d, ", matrix[i][j]);
    }
    Brain.Screen.newLine();
}

您可以修改二维数组中的特定元素:

// Assign the values in the matrix 2D array
int matrix[3][3] = {
  { 0, 1, 2 },
  { 3, 4, 5 },
  { 6, 7, 8 }
};

// Modify the color (in column 2) in row 0
matrix[0][1] = 200;

// Print the modified row from the matrix 2D array
for (int j = 0; j < 3; j++) {
    Brain.Screen.print("%d, ", matrix[0][j]);
}