if语句用来检验表达式的真假,如果为真则执行某些代码。
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 if(true) 7 cout << "This is always displayed!" << endl; 8 cout << endl; 9 if(false) 10 cout << "This is never displayed!" << endl << endl; 11 12 int score = 1000; 13 if(score) 14 cout << "At least you didn‘t score zero!" << endl << endl; 15 if(score>=250) 16 cout << "You scored 250 or more!" << endl; 17 if(score>=500) 18 { 19 cout << "You scored 500 or more.Nice!" << endl; 20 if(score >= 1000) 21 cout << "You scored 1000 or more.Impressive!" << endl; 22 } 23 24 return 0; 25 }
运行结果为:
注意:在if语句中验证的表达式的括号后面没有分号。如果加上分号,会形成一个与if语句成对的一个空语句,使if语句无效。
if可以让程序执行一条语句或一个包含多条语句的代码块。
这个代码块可以包含其他if语句。
if语句中包含另一个if语句称为嵌套。
如果嵌套太深的话,代码将很难读懂,最好限制在基层以内。
在if语句中加入else子句可以引入只有当被验证的表达式位false是才执行的代码。
形式:
if(expression)
statement;
else
statement;
1 // Score Rater 2.0 2 // Demonstrates an else clause 3 4 #include <iostream> 5 using namespace std; 6 7 int main() 8 { 9 int score; 10 cout << "Enter your score: "; 11 cin >> score; 12 13 if (score >= 1000) 14 { 15 cout << "You scored 1000 or more. Impressive!\n"; 16 } 17 else 18 { 19 cout << "You scored less than 1000.\n"; 20 } 21 22 return 0; 23 }
if (expression1) statement1; else if (expression2) statement2; ..... else if (expressionN) statementN; else statementN+1;
1 // Score Rater 3.0 2 // Demonstrates if else-if else suite 3 4 #include <iostream> 5 using namespace std; 6 7 int main() 8 { 9 int score; 10 cout << "Enter your score: "; 11 cin >> score; 12 13 if (score >= 1000) 14 { 15 cout << "You scored 1000 or more. Impressive!\n"; 16 } 17 else if (score >= 500) 18 { 19 cout << "You scored 500 or more. Nice.\n"; 20 } 21 else if (score >= 250) 22 { 23 cout << "You scored 250 or more. Decent.\n"; 24 } 25 else 26 { 27 cout << "You scored less than 250. Nothing to brag about.\n"; 28 } 29 30 return 0; 31 }
switch (choice) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementN+1; }
当程序运行到break语句时,会退出switch结构。
break和default的使用是可选的。
注意:switch语句只能用来比较int型(或其他可以当作int型处理的值,如char型或枚举型),switch语句不能用于其他任何类型。
1 // Menu Chooser 2 // Demonstrates the switch statement 3 4 #include <iostream> 5 using namespace std; 6 7 int main() 8 { 9 cout << "Difficulty Levels\n\n"; 10 cout << "1 - Easy\n"; 11 cout << "2 - Normal\n"; 12 cout << "3 - Hard\n\n"; 13 14 int choice; 15 cout << "Choice: "; 16 cin >> choice; 17 18 switch (choice) 19 { 20 case 1: 21 cout << "You picked Easy.\n"; 22 break; 23 case 2: 24 cout << "You picked Normal.\n"; 25 break; 26 case 3: 27 cout << "You picked Hard.\n"; 28 break; 29 default: 30 cout << "You made an illegal choice.\n"; 31 } 32 33 return 0; 34 }
几乎会在每种情况结尾添加break。
原文:https://www.cnblogs.com/wlyperfect/p/12398881.html