認識 Aero / 流程控制
流程控制
if / else
let x = 10;
if (x > 0) {
print("positive\n");
} else {
print("non-positive\n");
}條件必須是 bool 表達式,數字不能直接當條件。
if / else if 鏈
let score = 85;
if (score >= 90) {
print("A\n");
} else if (score >= 80) {
print("B\n");
} else if (score >= 70) {
print("C\n");
} else {
print("D\n");
}while 循環
let i = 0;
while (i < 5) {
print("%d\n", i);
i = i + 1;
}
// 輸出 0 1 2 3 4組合使用
// 打印 1 到 100 之間所有能被 3 整除的數
let i = 1;
while (i <= 100) {
if (i % 3 == 0) {
print("%d\n", i);
}
i = i + 1;
}當前沒有 break / continue:Aero 0.1 的 while 沒有 break 和 continue。想提前退出循環,用條件變量模擬。
// 模擬 break:找到第一個大於 100 的 7 的倍數
let i = 1;
let found = 0; // 0 = 假,1 = 真
while (i <= 1000 && found == 0) {
if (i % 7 == 0) {
print("%d\n", i);
found = 1;
}
i = i + 1;
}循環作用域坑
循環裏聲明"要跨循環保存"的變量,會被反覆重置:
let i = 0;
while (i < 5) {
let sum = 0; // 錯!每次循環 sum 都歸零
sum = sum + i;
i = i + 1;
}要在塊外聲明 sum,在循環裏累加。