导入
if/else 条件分支
学习使用 if、else 和 else if 语句来控制程序流程。
...
Basic if Statement
代码示例
1if (condition) { 2 // 条件为真时执行的代码 3}
1#include <iostream> 2 3int main() { 4 int score = 85; 5 6 std::cout << "Checking exam results...\n"; 7 8 // 简单的 if 语句 9 if (score >= 50) { 10 std::cout << "You passed the exam!\n"; 11 } 12 13 std::cout << "Grade check complete.\n"; 14 return 0; 15}
...
if-else conditional branching
代码示例
1if (condition) { 2 // 真分支 3} 4 5else { 6 // 假分支 7}
1#include <iostream> 2 3int main() { 4 int score = 49; 5 6 std::cout << "Checking exam results...\n"; 7 8 // 简单的 if 语句 9 if (score >= 50) { 10 std::cout << "You passed the exam!\n"; 11 } 12 else 13 { 14 std::cout << "You failed the exam!\n"; 15 } 16 17 std::cout << "Grade check complete.\n"; 18 return 0; 19}
...
Multiple elseif conditions
1#include <iostream> 2 3int main() { 4 int temperature = 0; 5 6 std::cout << "Analyzing weather...\n"; 7 8 if (temperature > 30) { 9 std::cout << "It's a hot day.\n"; 10 } 11 12 else if (temperature > 20) { 13 std::cout << "It's a nice day.\n"; 14 } 15 16 else if (temperature > 10) { 17 std::cout << "It's a bit chilly.\n"; 18 } 19 20 else { 21 std::cout << "It's cold!\n"; 22 } 23}
No configuration found for ID: 7a3f7a9306b89546f72a8516be0aeb358f1decc3b5e94d30e9afccbd76bd8195
...
Variable scope inside if block
1#include <iostream> 2 3int main() { 4 bool bonusEnabled = true; 5 6 if (bonusEnabled) { 7 int bonusPoints = 50; 8 std::cout << "Bonus applied: " << bonusPoints << "\n"; 9 } 10 11 std::cout << bonusPoints; // 错误! 12}
...
Nested if statements
1#include <iostream> 2 3int main() { 4 bool hasAccount = true; 5 bool knowsPassword = false; 6 7 if (hasAccount) { 8 std::cout << "Account found.\n"; 9 10 // 此检查仅在 hasAccount 为真时执行 11 if (knowsPassword) { 12 std::cout << "Login successful!\n"; 13 } else { 14 std::cout << "Incorrect password.\n"; 15 } 16 } else { 17 std::cout << "Please sign up first.\n"; 18 } 19 20 return 0; 21}
1if (initialization; condition) 2{ 3 ... 4}
1#include <iostream> 2 3int main() { 4 int balance = 500; 5 int cost = 600; 6 7 // 我们计算 'diff' 并立即检查它 8 // 'diff' 仅在 if/else 块内存在 9 if (int diff = balance - cost; diff >= 0) { 10 std::cout << "Purchase successful. Remaining: " << diff << "\n"; 11 } else { 12 std::cout << "Insufficient funds. Missing: " << -diff << "\n"; 13 } 14 15 // 'diff' 在此处不可访问,保持我们的工作区整洁。 16 return 0; 17}
1#include <iostream> 2 3int main() { 4 int x = 0; 5 6 // BUG: 赋值而非比较 7 if (x = 5) { 8 std::cout << "Condition is true\n"; 9 } 10 11 std::cout << "Value of x after if: " << x << "\n"; 12 13 return 0; 14}
1#include <iostream> 2 3int main() { 4 int health = 0; 5 6 // BUG: 分号使 if 语句立即结束 7 if (health > 0); 8 { 9 std::cout << "You are alive!\n"; 10 } 11 12 return 0; 13}