变量#
介绍#
变量用于存储数据,并允许你在整个程序中重复使用和操作这些数据。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 — 用于需要精确度的数学计算的高精度十进制数。
Float — 标准精度的十进制数,可用于测量或计算。
C 风格字符串 — 文本值,用于消息、标签或显示可读输出。
Boolean (bool) —
trueorfalsevalues for logic and decision-making.数组 — 固定大小的相同类型元素的集合。
2D 数组 — 数组的数组;非常适合表示行、网格或表格状数据。
Const — A variable declared with
constcannot be modified.
声明和赋值变量#
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;
命名变量时,必须遵守以下规则:
名称不能包含特殊字符(例如感叹号)。
名称不能以数字开头。
名称中不能包含空格。
The name cannot conflict with predefined VEXcode objects (for example,
Drivetrain).Variable names are case-sensitive (e.g.,
Distanceanddistanceare 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 main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
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 位)。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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#
float 类型存储十进制数。在大多数 VEX 项目中,除非内存使用量是主要考虑因素,否则通常优先使用 doubles 类型而不是 float 类型。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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[])是存储在字符数组中的字符序列。C 风格的字符串必须足够大,能够存储文本和一个空终止符。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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...");
}
}
布尔值可以在项目的任何阶段进行更改。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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#
数组是固定大小的同类型元素集合。最佳实践是在创建数组时就知道其长度并进行声明。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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#
二维数组通常用于表示网格、表格或矩阵。每一行代表一组特定的数据。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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();
}
}
您可以修改二维数组中的特定元素:
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// 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]);
}
}
Constant Variables#
A variable declared with const cannot be modified after it is initialized.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
const int maxSpeed = 100;
// maxSpeed can be used like a normal variable
Drivetrain.setDriveVelocity(maxSpeed, percent);
}