变量#
介绍#
变量存储数据,并允许您在整个程序中重用和操作数据。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++ is also strongly typed, which means you cannot perform operations on incompatible types without explicit conversion. For example:
int blocks = 2; // blocks is an integer
char rings[] = "4"; // rings is a string
int result = blocks + rings; // Creates a compilation error
此 API 解释了 C++ 中常见的变量类型。虽然并非详尽无遗,但它涵盖了您在实际工作中最可能使用的类型。
Local variables — Declared inside a function and only used within that scope; best for temporary or isolated values.
Global variables — Declared outside any function and used throughout the project; good for sharing data between functions.
Integer — Whole numbers used for counting, distances, or anything without decimals.
Double — High-precision decimal numbers for mathematical calculations requiring accuracy.
Float — Standard-precision decimal numbers, useful for measurements or calculations.
C-style String — Text values, used for messages, labels, or displaying readable output.
Boolean (bool) —
trueorfalsevalues for logic and decision-making.Arrays — Fixed-size collections of elements of the same type.
2D Arrays — Arrays of arrays; ideal for representing rows, grids, or table-like data.
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#
局部变量是在函数或代码块内部定义的。它们只能在该函数或代码块的范围内访问,在其外部不可见。
Define the function (outside of
int main())void show_local() { // This variable only exists inside this function int angle = 90; Brain.Screen.print("%d", angle); }Call the function inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code show_local(); }
局部变量通常用于存储仅与特定函数或程序部分相关的临时值。
Global Variables#
全局变量 定义在任何函数或块的外部。它们可以在程序的任何地方访问和读取,包括函数内部。
注意:全局变量可以在程序的任何位置访问,这使得它们可以方便地跨函数共享数据。然而,过度依赖全局变量可能会导致意想不到的副作用,因为在程序的某个部分对变量的更改可能会对其他部分产生不可预测的影响。因此,在可能的情况下,通常优先使用局部变量,因为它们将变量的作用域限制在其定义的特定函数内。这可以降低冲突的可能性并使调试更容易。
Define the function (outside of
int main())// 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(); }Call the function inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ 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 function (outside of
int main())// 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(); }Call the function inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code increase_count(); increase_count(); }
数据类型#
C++ supports several types of data that can be stored in variables. Some types can be reassigned, while others allow individual elements to be modified. Below are the most commonly used types:
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#
A float stores decimal numbers. In most VEX projects, doubles are preferred over floats unless memory usage is a concern.
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#
A C-style string (char variable_name[]) is a sequence of characters stored in a character array. C-style strings must be large enough to store the text and a null terminator.
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);
}