變數#
介紹#
變數用於儲存數據,並允許你在整個程式中重複使用和操作這些數據。 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 風格字串 — 文字值,用於訊息、標籤或顯示可讀輸出。
布林值(bool) —
true或false用於邏輯和決策的值。數組 — 固定大小的相同類型元素的集合。
2D 陣列 — 陣列的陣列;非常適合表示行、網格或表格狀資料。
Const — 用
const宣告的變數不能被修改。
聲明和賦值變數#
要在 C++ 中建立變量,必須先宣告其類型,後面跟著變數名,然後可以選擇性地使用 = 運算子賦值:
int distance = 100;
命名變數時,必須遵守以下規則:
名稱不能包含特殊字元(例如感嘆號)。
名稱不能以數字開頭。
名稱中不能包含空格。
名稱不能與預先定義的 VEXcode 物件衝突(例如,
Drivetrain)。名稱不能是 C++ 保留關鍵字(例如,
intforfor)。變數名稱區分大小寫(例如,
Distance和distance是不同的變數)。
Local Variables#
局部變數是在函數或程式碼區塊內部定義的。它們只能在該函數或程式碼區塊的作用域內訪問,在外部不可見。
定義函數(在
int main()之外)void show_local() { // This variable only exists inside this function int angle = 90; Brain.Screen.print("%d", angle); }呼叫內部函數
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#
全域變數 定義在任何函數或程式碼區塊的外部。它們可以在程式中的任何位置存取和讀取,包括函數內部。
注意: 全域變數 可以在程式的任何位置訪問,這使得跨函數共享資料變得非常方便。然而,過度依賴全域變數可能會導致意想不到的副作用,因為程式中某個部分的變數變更可能會對其他部分產生不可預測的影響。因此,通常建議盡可能使用局部變數,因為它們將變數的作用域限制在定義它的特定函數中。這可以降低衝突的可能性,並使調試更加容易。
定義函數(在
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(); }呼叫內部函數
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); }
在 C++ 中,可以直接在函數內部存取和修改全域變量,無需任何特殊關鍵字。但是,如果存在同名的局部變量,則可以使用作用域解析運算子 :: 來存取全域變數。
定義函數(在
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(); }呼叫內部函數
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++ 支援多種可儲存在變數中的資料類型。有些類型可以重新賦值,而有些類型則允許修改單一元素。以下是最常用的資料類型:
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#
布林值(bool)表示 true 或 false)。
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#
陣列是固定大小的同類型元素集合,從索引 0 開始。最佳實踐是在創建數組時就知道其長度並進行聲明。
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 distances 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#
用 const 宣告的變數在初始化後不能修改。
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);
}